1
# Copyright (C) 2005, 2006, 2007, 2008 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
43
from bzrlib.lazy_import import lazy_import
44
lazy_import(globals(), """
45
from bisect import bisect_left
59
conflicts as _mod_conflicts,
67
revision as _mod_revision,
82
from bzrlib.transport import get_transport
84
from bzrlib.workingtree_4 import WorkingTreeFormat4
87
from bzrlib import symbol_versioning
88
from bzrlib.decorators import needs_read_lock, needs_write_lock
89
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
90
from bzrlib.lockable_files import LockableFiles
91
from bzrlib.lockdir import LockDir
92
import bzrlib.mutabletree
93
from bzrlib.mutabletree import needs_tree_write_lock
94
from bzrlib import osutils
95
from bzrlib.osutils import (
107
from bzrlib.trace import mutter, note
108
from bzrlib.transport.local import LocalTransport
109
from bzrlib.progress import DummyProgress, ProgressPhase
110
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
111
from bzrlib.rio import RioReader, rio_file, Stanza
112
from bzrlib.symbol_versioning import (deprecated_passed,
115
DEPRECATED_PARAMETER,
119
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
120
CONFLICT_HEADER_1 = "BZR conflict list format 1"
122
ERROR_PATH_NOT_FOUND = 3 # WindowsError errno code, equivalent to ENOENT
125
class TreeEntry(object):
126
"""An entry that implements the minimum interface used by commands.
128
This needs further inspection, it may be better to have
129
InventoryEntries without ids - though that seems wrong. For now,
130
this is a parallel hierarchy to InventoryEntry, and needs to become
131
one of several things: decorates to that hierarchy, children of, or
133
Another note is that these objects are currently only used when there is
134
no InventoryEntry available - i.e. for unversioned objects.
135
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
138
def __eq__(self, other):
139
# yes, this us ugly, TODO: best practice __eq__ style.
140
return (isinstance(other, TreeEntry)
141
and other.__class__ == self.__class__)
143
def kind_character(self):
147
class TreeDirectory(TreeEntry):
148
"""See TreeEntry. This is a directory in a working tree."""
150
def __eq__(self, other):
151
return (isinstance(other, TreeDirectory)
152
and other.__class__ == self.__class__)
154
def kind_character(self):
158
class TreeFile(TreeEntry):
159
"""See TreeEntry. This is a regular file in a working tree."""
161
def __eq__(self, other):
162
return (isinstance(other, TreeFile)
163
and other.__class__ == self.__class__)
165
def kind_character(self):
169
class TreeLink(TreeEntry):
170
"""See TreeEntry. This is a symlink in a working tree."""
172
def __eq__(self, other):
173
return (isinstance(other, TreeLink)
174
and other.__class__ == self.__class__)
176
def kind_character(self):
180
class WorkingTree(bzrlib.mutabletree.MutableTree):
181
"""Working copy tree.
183
The inventory is held in the `Branch` working-inventory, and the
184
files are in a directory on disk.
186
It is possible for a `WorkingTree` to have a filename which is
187
not listed in the Inventory and vice versa.
190
# override this to set the strategy for storing views
191
def _make_views(self):
192
return views.DisabledViews(self)
194
def __init__(self, basedir='.',
195
branch=DEPRECATED_PARAMETER,
201
"""Construct a WorkingTree instance. This is not a public API.
203
:param branch: A branch to override probing for the branch.
205
self._format = _format
206
self.bzrdir = _bzrdir
208
raise errors.BzrError("Please use bzrdir.open_workingtree or "
209
"WorkingTree.open() to obtain a WorkingTree.")
210
basedir = safe_unicode(basedir)
211
mutter("opening working tree %r", basedir)
212
if deprecated_passed(branch):
213
self._branch = branch
215
self._branch = self.bzrdir.open_branch()
216
self.basedir = realpath(basedir)
217
# if branch is at our basedir and is a format 6 or less
218
if isinstance(self._format, WorkingTreeFormat2):
219
# share control object
220
self._control_files = self.branch.control_files
222
# assume all other formats have their own control files.
223
self._control_files = _control_files
224
self._transport = self._control_files._transport
225
# update the whole cache up front and write to disk if anything changed;
226
# in the future we might want to do this more selectively
227
# two possible ways offer themselves : in self._unlock, write the cache
228
# if needed, or, when the cache sees a change, append it to the hash
229
# cache file, and have the parser take the most recent entry for a
231
wt_trans = self.bzrdir.get_workingtree_transport(None)
232
cache_filename = wt_trans.local_abspath('stat-cache')
233
self._hashcache = hashcache.HashCache(basedir, cache_filename,
234
self.bzrdir._get_file_mode())
237
# is this scan needed ? it makes things kinda slow.
244
if _inventory is None:
245
# This will be acquired on lock_read() or lock_write()
246
self._inventory_is_modified = False
247
self._inventory = None
249
# the caller of __init__ has provided an inventory,
250
# we assume they know what they are doing - as its only
251
# the Format factory and creation methods that are
252
# permitted to do this.
253
self._set_inventory(_inventory, dirty=False)
254
self._detect_case_handling()
255
self._rules_searcher = None
256
self.views = self._make_views()
258
def _detect_case_handling(self):
259
wt_trans = self.bzrdir.get_workingtree_transport(None)
261
wt_trans.stat("FoRMaT")
262
except errors.NoSuchFile:
263
self.case_sensitive = True
265
self.case_sensitive = False
267
self._setup_directory_is_tree_reference()
270
fget=lambda self: self._branch,
271
doc="""The branch this WorkingTree is connected to.
273
This cannot be set - it is reflective of the actual disk structure
274
the working tree has been constructed from.
277
def break_lock(self):
278
"""Break a lock if one is present from another instance.
280
Uses the ui factory to ask for confirmation if the lock may be from
283
This will probe the repository for its lock as well.
285
self._control_files.break_lock()
286
self.branch.break_lock()
288
def requires_rich_root(self):
289
return self._format.requires_rich_root
291
def supports_tree_reference(self):
294
def supports_views(self):
295
return self.views.supports_views()
297
def _set_inventory(self, inv, dirty):
298
"""Set the internal cached inventory.
300
:param inv: The inventory to set.
301
:param dirty: A boolean indicating whether the inventory is the same
302
logical inventory as whats on disk. If True the inventory is not
303
the same and should be written to disk or data will be lost, if
304
False then the inventory is the same as that on disk and any
305
serialisation would be unneeded overhead.
307
self._inventory = inv
308
self._inventory_is_modified = dirty
311
def open(path=None, _unsupported=False):
312
"""Open an existing working tree at path.
316
path = osutils.getcwd()
317
control = bzrdir.BzrDir.open(path, _unsupported)
318
return control.open_workingtree(_unsupported)
321
def open_containing(path=None):
322
"""Open an existing working tree which has its root about path.
324
This probes for a working tree at path and searches upwards from there.
326
Basically we keep looking up until we find the control directory or
327
run into /. If there isn't one, raises NotBranchError.
328
TODO: give this a new exception.
329
If there is one, it is returned, along with the unused portion of path.
331
:return: The WorkingTree that contains 'path', and the rest of path
334
path = osutils.getcwd()
335
control, relpath = bzrdir.BzrDir.open_containing(path)
337
return control.open_workingtree(), relpath
340
def open_downlevel(path=None):
341
"""Open an unsupported working tree.
343
Only intended for advanced situations like upgrading part of a bzrdir.
345
return WorkingTree.open(path, _unsupported=True)
348
def find_trees(location):
349
def list_current(transport):
350
return [d for d in transport.list_dir('') if d != '.bzr']
351
def evaluate(bzrdir):
353
tree = bzrdir.open_workingtree()
354
except errors.NoWorkingTree:
358
transport = get_transport(location)
359
iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
360
list_current=list_current)
361
return [t for t in iterator if t is not None]
363
# should be deprecated - this is slow and in any case treating them as a
364
# container is (we now know) bad style -- mbp 20070302
365
## @deprecated_method(zero_fifteen)
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)):
377
def all_file_ids(self):
378
"""See Tree.iter_all_file_ids"""
379
return set(self.inventory)
382
return "<%s of %s>" % (self.__class__.__name__,
383
getattr(self, 'basedir', None))
385
def abspath(self, filename):
386
return pathjoin(self.basedir, filename)
388
def basis_tree(self):
389
"""Return RevisionTree for the current last revision.
391
If the left most parent is a ghost then the returned tree will be an
392
empty tree - one obtained by calling
393
repository.revision_tree(NULL_REVISION).
396
revision_id = self.get_parent_ids()[0]
398
# no parents, return an empty revision tree.
399
# in the future this should return the tree for
400
# 'empty:' - the implicit root empty tree.
401
return self.branch.repository.revision_tree(
402
_mod_revision.NULL_REVISION)
404
return self.revision_tree(revision_id)
405
except errors.NoSuchRevision:
407
# No cached copy available, retrieve from the repository.
408
# FIXME? RBC 20060403 should we cache the inventory locally
411
return self.branch.repository.revision_tree(revision_id)
412
except (errors.RevisionNotPresent, errors.NoSuchRevision):
413
# the basis tree *may* be a ghost or a low level error may have
414
# occured. If the revision is present, its a problem, if its not
416
if self.branch.repository.has_revision(revision_id):
418
# the basis tree is a ghost so return an empty tree.
419
return self.branch.repository.revision_tree(
420
_mod_revision.NULL_REVISION)
423
self._flush_ignore_list_cache()
425
def relpath(self, path):
426
"""Return the local path portion from a given path.
428
The path may be absolute or relative. If its a relative path it is
429
interpreted relative to the python current working directory.
431
return osutils.relpath(self.basedir, path)
433
def has_filename(self, filename):
434
return osutils.lexists(self.abspath(filename))
436
def get_file(self, file_id, path=None):
437
return self.get_file_with_stat(file_id, path)[0]
439
def get_file_with_stat(self, file_id, path=None, _fstat=os.fstat):
440
"""See MutableTree.get_file_with_stat."""
442
path = self.id2path(file_id)
443
file_obj = self.get_file_byname(path)
444
return (file_obj, _fstat(file_obj.fileno()))
446
def get_file_byname(self, filename):
447
return file(self.abspath(filename), 'rb')
449
def get_file_lines(self, file_id, path=None):
450
"""See Tree.get_file_lines()"""
451
file = self.get_file(file_id, path)
453
return file.readlines()
458
def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
459
"""See Tree.annotate_iter
461
This implementation will use the basis tree implementation if possible.
462
Lines not in the basis are attributed to CURRENT_REVISION
464
If there are pending merges, lines added by those merges will be
465
incorrectly attributed to CURRENT_REVISION (but after committing, the
466
attribution will be correct).
468
basis = self.basis_tree()
471
changes = self.iter_changes(basis, True, [self.id2path(file_id)],
472
require_versioned=True).next()
473
changed_content, kind = changes[2], changes[6]
474
if not changed_content:
475
return basis.annotate_iter(file_id)
479
if kind[0] != 'file':
482
old_lines = list(basis.annotate_iter(file_id))
484
for tree in self.branch.repository.revision_trees(
485
self.get_parent_ids()[1:]):
486
if file_id not in tree:
488
old.append(list(tree.annotate_iter(file_id)))
489
return annotate.reannotate(old, self.get_file(file_id).readlines(),
494
def _get_ancestors(self, default_revision):
495
ancestors = set([default_revision])
496
for parent_id in self.get_parent_ids():
497
ancestors.update(self.branch.repository.get_ancestry(
498
parent_id, topo_sorted=False))
501
def get_parent_ids(self):
502
"""See Tree.get_parent_ids.
504
This implementation reads the pending merges list and last_revision
505
value and uses that to decide what the parents list should be.
507
last_rev = _mod_revision.ensure_null(self._last_revision())
508
if _mod_revision.NULL_REVISION == last_rev:
513
merges_file = self._transport.get('pending-merges')
514
except errors.NoSuchFile:
517
for l in merges_file.readlines():
518
revision_id = l.rstrip('\n')
519
parents.append(revision_id)
523
def get_root_id(self):
524
"""Return the id of this trees root"""
525
return self._inventory.root.file_id
527
def _get_store_filename(self, file_id):
528
## XXX: badly named; this is not in the store at all
529
return self.abspath(self.id2path(file_id))
532
def clone(self, to_bzrdir, revision_id=None):
533
"""Duplicate this working tree into to_bzr, including all state.
535
Specifically modified files are kept as modified, but
536
ignored and unknown files are discarded.
538
If you want to make a new line of development, see bzrdir.sprout()
541
If not None, the cloned tree will have its last revision set to
542
revision, and and difference between the source trees last revision
543
and this one merged in.
545
# assumes the target bzr dir format is compatible.
546
result = to_bzrdir.create_workingtree()
547
self.copy_content_into(result, revision_id)
551
def copy_content_into(self, tree, revision_id=None):
552
"""Copy the current content and user files of this tree into tree."""
553
tree.set_root_id(self.get_root_id())
554
if revision_id is None:
555
merge.transform_tree(tree, self)
557
# TODO now merge from tree.last_revision to revision (to preserve
558
# user local changes)
559
merge.transform_tree(tree, self)
560
tree.set_parent_ids([revision_id])
562
def id2abspath(self, file_id):
563
return self.abspath(self.id2path(file_id))
565
def has_id(self, file_id):
566
# files that have been deleted are excluded
568
if not inv.has_id(file_id):
570
path = inv.id2path(file_id)
571
return osutils.lexists(self.abspath(path))
573
def has_or_had_id(self, file_id):
574
if file_id == self.inventory.root.file_id:
576
return self.inventory.has_id(file_id)
578
__contains__ = has_id
580
def get_file_size(self, file_id):
581
"""See Tree.get_file_size"""
583
return os.path.getsize(self.id2abspath(file_id))
585
if e.errno != errno.ENOENT:
591
def get_file_sha1(self, file_id, path=None, stat_value=None):
593
path = self._inventory.id2path(file_id)
594
return self._hashcache.get_sha1(path, stat_value)
596
def get_file_mtime(self, file_id, path=None):
598
path = self.inventory.id2path(file_id)
599
return os.lstat(self.abspath(path)).st_mtime
601
def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
602
file_id = self.path2id(path)
603
return self._inventory[file_id].executable
605
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
606
mode = stat_result.st_mode
607
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
609
if not supports_executable():
610
def is_executable(self, file_id, path=None):
611
return self._inventory[file_id].executable
613
_is_executable_from_path_and_stat = \
614
_is_executable_from_path_and_stat_from_basis
616
def is_executable(self, file_id, path=None):
618
path = self.id2path(file_id)
619
mode = os.lstat(self.abspath(path)).st_mode
620
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
622
_is_executable_from_path_and_stat = \
623
_is_executable_from_path_and_stat_from_stat
625
@needs_tree_write_lock
626
def _add(self, files, ids, kinds):
627
"""See MutableTree._add."""
628
# TODO: Re-adding a file that is removed in the working copy
629
# should probably put it back with the previous ID.
630
# the read and write working inventory should not occur in this
631
# function - they should be part of lock_write and unlock.
633
for f, file_id, kind in zip(files, ids, kinds):
635
inv.add_path(f, kind=kind)
637
inv.add_path(f, kind=kind, file_id=file_id)
638
self._inventory_is_modified = True
640
@needs_tree_write_lock
641
def _gather_kinds(self, files, kinds):
642
"""See MutableTree._gather_kinds."""
643
for pos, f in enumerate(files):
644
if kinds[pos] is None:
645
fullpath = normpath(self.abspath(f))
647
kinds[pos] = file_kind(fullpath)
649
if e.errno == errno.ENOENT:
650
raise errors.NoSuchFile(fullpath)
653
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
654
"""Add revision_id as a parent.
656
This is equivalent to retrieving the current list of parent ids
657
and setting the list to its value plus revision_id.
659
:param revision_id: The revision id to add to the parent list. It may
660
be a ghost revision as long as its not the first parent to be added,
661
or the allow_leftmost_as_ghost parameter is set True.
662
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
664
parents = self.get_parent_ids() + [revision_id]
665
self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
666
or allow_leftmost_as_ghost)
668
@needs_tree_write_lock
669
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
670
"""Add revision_id, tree tuple as a parent.
672
This is equivalent to retrieving the current list of parent trees
673
and setting the list to its value plus parent_tuple. See also
674
add_parent_tree_id - if you only have a parent id available it will be
675
simpler to use that api. If you have the parent already available, using
676
this api is preferred.
678
:param parent_tuple: The (revision id, tree) to add to the parent list.
679
If the revision_id is a ghost, pass None for the tree.
680
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
682
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
683
if len(parent_ids) > 1:
684
# the leftmost may have already been a ghost, preserve that if it
686
allow_leftmost_as_ghost = True
687
self.set_parent_ids(parent_ids,
688
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
690
@needs_tree_write_lock
691
def add_pending_merge(self, *revision_ids):
692
# TODO: Perhaps should check at this point that the
693
# history of the revision is actually present?
694
parents = self.get_parent_ids()
696
for rev_id in revision_ids:
697
if rev_id in parents:
699
parents.append(rev_id)
702
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
704
def path_content_summary(self, path, _lstat=os.lstat,
705
_mapper=osutils.file_kind_from_stat_mode):
706
"""See Tree.path_content_summary."""
707
abspath = self.abspath(path)
709
stat_result = _lstat(abspath)
711
if getattr(e, 'errno', None) == errno.ENOENT:
713
return ('missing', None, None, None)
714
# propagate other errors
716
kind = _mapper(stat_result.st_mode)
718
size = stat_result.st_size
719
# try for a stat cache lookup
720
executable = self._is_executable_from_path_and_stat(path, stat_result)
721
return (kind, size, executable, self._sha_from_stat(
723
elif kind == 'directory':
724
# perhaps it looks like a plain directory, but it's really a
726
if self._directory_is_tree_reference(path):
727
kind = 'tree-reference'
728
return kind, None, None, None
729
elif kind == 'symlink':
730
return ('symlink', None, None, os.readlink(abspath))
732
return (kind, None, None, None)
734
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
735
"""Common ghost checking functionality from set_parent_*.
737
This checks that the left hand-parent exists if there are any
740
if len(revision_ids) > 0:
741
leftmost_id = revision_ids[0]
742
if (not allow_leftmost_as_ghost and not
743
self.branch.repository.has_revision(leftmost_id)):
744
raise errors.GhostRevisionUnusableHere(leftmost_id)
746
def _set_merges_from_parent_ids(self, parent_ids):
747
merges = parent_ids[1:]
748
self._transport.put_bytes('pending-merges', '\n'.join(merges),
749
mode=self._control_files._file_mode)
751
def _filter_parent_ids_by_ancestry(self, revision_ids):
752
"""Check that all merged revisions are proper 'heads'.
754
This will always return the first revision_id, and any merged revisions
757
if len(revision_ids) == 0:
759
graph = self.branch.repository.get_graph()
760
heads = graph.heads(revision_ids)
761
new_revision_ids = revision_ids[:1]
762
for revision_id in revision_ids[1:]:
763
if revision_id in heads and revision_id not in new_revision_ids:
764
new_revision_ids.append(revision_id)
765
if new_revision_ids != revision_ids:
766
trace.mutter('requested to set revision_ids = %s,'
767
' but filtered to %s', revision_ids, new_revision_ids)
768
return new_revision_ids
770
@needs_tree_write_lock
771
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
772
"""Set the parent ids to revision_ids.
774
See also set_parent_trees. This api will try to retrieve the tree data
775
for each element of revision_ids from the trees repository. If you have
776
tree data already available, it is more efficient to use
777
set_parent_trees rather than set_parent_ids. set_parent_ids is however
778
an easier API to use.
780
:param revision_ids: The revision_ids to set as the parent ids of this
781
working tree. Any of these may be ghosts.
783
self._check_parents_for_ghosts(revision_ids,
784
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
785
for revision_id in revision_ids:
786
_mod_revision.check_not_reserved_id(revision_id)
788
revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
790
if len(revision_ids) > 0:
791
self.set_last_revision(revision_ids[0])
793
self.set_last_revision(_mod_revision.NULL_REVISION)
795
self._set_merges_from_parent_ids(revision_ids)
797
@needs_tree_write_lock
798
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
799
"""See MutableTree.set_parent_trees."""
800
parent_ids = [rev for (rev, tree) in parents_list]
801
for revision_id in parent_ids:
802
_mod_revision.check_not_reserved_id(revision_id)
804
self._check_parents_for_ghosts(parent_ids,
805
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
807
parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
809
if len(parent_ids) == 0:
810
leftmost_parent_id = _mod_revision.NULL_REVISION
811
leftmost_parent_tree = None
813
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
815
if self._change_last_revision(leftmost_parent_id):
816
if leftmost_parent_tree is None:
817
# If we don't have a tree, fall back to reading the
818
# parent tree from the repository.
819
self._cache_basis_inventory(leftmost_parent_id)
821
inv = leftmost_parent_tree.inventory
822
xml = self._create_basis_xml_from_inventory(
823
leftmost_parent_id, inv)
824
self._write_basis_inventory(xml)
825
self._set_merges_from_parent_ids(parent_ids)
827
@needs_tree_write_lock
828
def set_pending_merges(self, rev_list):
829
parents = self.get_parent_ids()
830
leftmost = parents[:1]
831
new_parents = leftmost + rev_list
832
self.set_parent_ids(new_parents)
834
@needs_tree_write_lock
835
def set_merge_modified(self, modified_hashes):
837
for file_id, hash in modified_hashes.iteritems():
838
yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
839
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
841
def _sha_from_stat(self, path, stat_result):
842
"""Get a sha digest from the tree's stat cache.
844
The default implementation assumes no stat cache is present.
846
:param path: The path.
847
:param stat_result: The stat result being looked up.
851
def _put_rio(self, filename, stanzas, header):
852
self._must_be_locked()
853
my_file = rio_file(stanzas, header)
854
self._transport.put_file(filename, my_file,
855
mode=self._control_files._file_mode)
857
@needs_write_lock # because merge pulls data into the branch.
858
def merge_from_branch(self, branch, to_revision=None, from_revision=None,
860
"""Merge from a branch into this working tree.
862
:param branch: The branch to merge from.
863
:param to_revision: If non-None, the merge will merge to to_revision,
864
but not beyond it. to_revision does not need to be in the history
865
of the branch when it is supplied. If None, to_revision defaults to
866
branch.last_revision().
868
from bzrlib.merge import Merger, Merge3Merger
869
pb = bzrlib.ui.ui_factory.nested_progress_bar()
871
merger = Merger(self.branch, this_tree=self, pb=pb)
872
merger.pp = ProgressPhase("Merge phase", 5, pb)
873
merger.pp.next_phase()
874
# check that there are no
876
merger.check_basis(check_clean=True, require_commits=False)
877
if to_revision is None:
878
to_revision = _mod_revision.ensure_null(branch.last_revision())
879
merger.other_rev_id = to_revision
880
if _mod_revision.is_null(merger.other_rev_id):
881
raise errors.NoCommits(branch)
882
self.branch.fetch(branch, last_revision=merger.other_rev_id)
883
merger.other_basis = merger.other_rev_id
884
merger.other_tree = self.branch.repository.revision_tree(
886
merger.other_branch = branch
887
merger.pp.next_phase()
888
if from_revision is None:
891
merger.set_base_revision(from_revision, branch)
892
if merger.base_rev_id == merger.other_rev_id:
893
raise errors.PointlessMerge
894
merger.backup_files = False
895
if merge_type is None:
896
merger.merge_type = Merge3Merger
898
merger.merge_type = merge_type
899
merger.set_interesting_files(None)
900
merger.show_base = False
901
merger.reprocess = False
902
conflicts = merger.do_merge()
909
def merge_modified(self):
910
"""Return a dictionary of files modified by a merge.
912
The list is initialized by WorkingTree.set_merge_modified, which is
913
typically called after we make some automatic updates to the tree
916
This returns a map of file_id->sha1, containing only files which are
917
still in the working inventory and have that text hash.
920
hashfile = self._transport.get('merge-hashes')
921
except errors.NoSuchFile:
926
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
927
raise errors.MergeModifiedFormatError()
928
except StopIteration:
929
raise errors.MergeModifiedFormatError()
930
for s in RioReader(hashfile):
931
# RioReader reads in Unicode, so convert file_ids back to utf8
932
file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
933
if file_id not in self.inventory:
935
text_hash = s.get("hash")
936
if text_hash == self.get_file_sha1(file_id):
937
merge_hashes[file_id] = text_hash
943
def mkdir(self, path, file_id=None):
944
"""See MutableTree.mkdir()."""
946
file_id = generate_ids.gen_file_id(os.path.basename(path))
947
os.mkdir(self.abspath(path))
948
self.add(path, file_id, 'directory')
951
def get_symlink_target(self, file_id):
952
return os.readlink(self.id2abspath(file_id))
955
def subsume(self, other_tree):
956
def add_children(inventory, entry):
957
for child_entry in entry.children.values():
958
inventory._byid[child_entry.file_id] = child_entry
959
if child_entry.kind == 'directory':
960
add_children(inventory, child_entry)
961
if other_tree.get_root_id() == self.get_root_id():
962
raise errors.BadSubsumeSource(self, other_tree,
963
'Trees have the same root')
965
other_tree_path = self.relpath(other_tree.basedir)
966
except errors.PathNotChild:
967
raise errors.BadSubsumeSource(self, other_tree,
968
'Tree is not contained by the other')
969
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
970
if new_root_parent is None:
971
raise errors.BadSubsumeSource(self, other_tree,
972
'Parent directory is not versioned.')
973
# We need to ensure that the result of a fetch will have a
974
# versionedfile for the other_tree root, and only fetching into
975
# RepositoryKnit2 guarantees that.
976
if not self.branch.repository.supports_rich_root():
977
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
978
other_tree.lock_tree_write()
980
new_parents = other_tree.get_parent_ids()
981
other_root = other_tree.inventory.root
982
other_root.parent_id = new_root_parent
983
other_root.name = osutils.basename(other_tree_path)
984
self.inventory.add(other_root)
985
add_children(self.inventory, other_root)
986
self._write_inventory(self.inventory)
987
# normally we don't want to fetch whole repositories, but i think
988
# here we really do want to consolidate the whole thing.
989
for parent_id in other_tree.get_parent_ids():
990
self.branch.fetch(other_tree.branch, parent_id)
991
self.add_parent_tree_id(parent_id)
994
other_tree.bzrdir.retire_bzrdir()
996
def _setup_directory_is_tree_reference(self):
997
if self._branch.repository._format.supports_tree_reference:
998
self._directory_is_tree_reference = \
999
self._directory_may_be_tree_reference
1001
self._directory_is_tree_reference = \
1002
self._directory_is_never_tree_reference
1004
def _directory_is_never_tree_reference(self, relpath):
1007
def _directory_may_be_tree_reference(self, relpath):
1008
# as a special case, if a directory contains control files then
1009
# it's a tree reference, except that the root of the tree is not
1010
return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
1011
# TODO: We could ask all the control formats whether they
1012
# recognize this directory, but at the moment there's no cheap api
1013
# to do that. Since we probably can only nest bzr checkouts and
1014
# they always use this name it's ok for now. -- mbp 20060306
1016
# FIXME: There is an unhandled case here of a subdirectory
1017
# containing .bzr but not a branch; that will probably blow up
1018
# when you try to commit it. It might happen if there is a
1019
# checkout in a subdirectory. This can be avoided by not adding
1022
@needs_tree_write_lock
1023
def extract(self, file_id, format=None):
1024
"""Extract a subtree from this tree.
1026
A new branch will be created, relative to the path for this tree.
1030
segments = osutils.splitpath(path)
1031
transport = self.branch.bzrdir.root_transport
1032
for name in segments:
1033
transport = transport.clone(name)
1034
transport.ensure_base()
1037
sub_path = self.id2path(file_id)
1038
branch_transport = mkdirs(sub_path)
1040
format = self.bzrdir.cloning_metadir()
1041
branch_transport.ensure_base()
1042
branch_bzrdir = format.initialize_on_transport(branch_transport)
1044
repo = branch_bzrdir.find_repository()
1045
except errors.NoRepositoryPresent:
1046
repo = branch_bzrdir.create_repository()
1047
if not repo.supports_rich_root():
1048
raise errors.RootNotRich()
1049
new_branch = branch_bzrdir.create_branch()
1050
new_branch.pull(self.branch)
1051
for parent_id in self.get_parent_ids():
1052
new_branch.fetch(self.branch, parent_id)
1053
tree_transport = self.bzrdir.root_transport.clone(sub_path)
1054
if tree_transport.base != branch_transport.base:
1055
tree_bzrdir = format.initialize_on_transport(tree_transport)
1056
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1058
tree_bzrdir = branch_bzrdir
1059
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1060
wt.set_parent_ids(self.get_parent_ids())
1061
my_inv = self.inventory
1062
child_inv = Inventory(root_id=None)
1063
new_root = my_inv[file_id]
1064
my_inv.remove_recursive_id(file_id)
1065
new_root.parent_id = None
1066
child_inv.add(new_root)
1067
self._write_inventory(my_inv)
1068
wt._write_inventory(child_inv)
1071
def _serialize(self, inventory, out_file):
1072
xml5.serializer_v5.write_inventory(self._inventory, out_file,
1075
def _deserialize(selt, in_file):
1076
return xml5.serializer_v5.read_inventory(in_file)
1079
"""Write the in memory inventory to disk."""
1080
# TODO: Maybe this should only write on dirty ?
1081
if self._control_files._lock_mode != 'w':
1082
raise errors.NotWriteLocked(self)
1084
self._serialize(self._inventory, sio)
1086
self._transport.put_file('inventory', sio,
1087
mode=self._control_files._file_mode)
1088
self._inventory_is_modified = False
1090
def _kind(self, relpath):
1091
return osutils.file_kind(self.abspath(relpath))
1093
def list_files(self, include_root=False):
1094
"""Recursively list all files as (path, class, kind, id, entry).
1096
Lists, but does not descend into unversioned directories.
1098
This does not include files that have been deleted in this
1101
Skips the control directory.
1103
# list_files is an iterator, so @needs_read_lock doesn't work properly
1104
# with it. So callers should be careful to always read_lock the tree.
1105
if not self.is_locked():
1106
raise errors.ObjectNotLocked(self)
1108
inv = self.inventory
1109
if include_root is True:
1110
yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1111
# Convert these into local objects to save lookup times
1112
pathjoin = osutils.pathjoin
1113
file_kind = self._kind
1115
# transport.base ends in a slash, we want the piece
1116
# between the last two slashes
1117
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1119
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1121
# directory file_id, relative path, absolute path, reverse sorted children
1122
children = os.listdir(self.basedir)
1124
# jam 20060527 The kernel sized tree seems equivalent whether we
1125
# use a deque and popleft to keep them sorted, or if we use a plain
1126
# list and just reverse() them.
1127
children = collections.deque(children)
1128
stack = [(inv.root.file_id, u'', self.basedir, children)]
1130
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1133
f = children.popleft()
1134
## TODO: If we find a subdirectory with its own .bzr
1135
## directory, then that is a separate tree and we
1136
## should exclude it.
1138
# the bzrdir for this tree
1139
if transport_base_dir == f:
1142
# we know that from_dir_relpath and from_dir_abspath never end in a slash
1143
# and 'f' doesn't begin with one, we can do a string op, rather
1144
# than the checks of pathjoin(), all relative paths will have an extra slash
1146
fp = from_dir_relpath + '/' + f
1149
fap = from_dir_abspath + '/' + f
1151
f_ie = inv.get_child(from_dir_id, f)
1154
elif self.is_ignored(fp[1:]):
1157
# we may not have found this file, because of a unicode issue
1158
f_norm, can_access = osutils.normalized_filename(f)
1159
if f == f_norm or not can_access:
1160
# No change, so treat this file normally
1163
# this file can be accessed by a normalized path
1164
# check again if it is versioned
1165
# these lines are repeated here for performance
1167
fp = from_dir_relpath + '/' + f
1168
fap = from_dir_abspath + '/' + f
1169
f_ie = inv.get_child(from_dir_id, f)
1172
elif self.is_ignored(fp[1:]):
1179
# make a last minute entry
1181
yield fp[1:], c, fk, f_ie.file_id, f_ie
1184
yield fp[1:], c, fk, None, fk_entries[fk]()
1186
yield fp[1:], c, fk, None, TreeEntry()
1189
if fk != 'directory':
1192
# But do this child first
1193
new_children = os.listdir(fap)
1195
new_children = collections.deque(new_children)
1196
stack.append((f_ie.file_id, fp, fap, new_children))
1197
# Break out of inner loop,
1198
# so that we start outer loop with child
1201
# if we finished all children, pop it off the stack
1204
@needs_tree_write_lock
1205
def move(self, from_paths, to_dir=None, after=False, **kwargs):
1208
to_dir must exist in the inventory.
1210
If to_dir exists and is a directory, the files are moved into
1211
it, keeping their old names.
1213
Note that to_dir is only the last component of the new name;
1214
this doesn't change the directory.
1216
For each entry in from_paths the move mode will be determined
1219
The first mode moves the file in the filesystem and updates the
1220
inventory. The second mode only updates the inventory without
1221
touching the file on the filesystem. This is the new mode introduced
1224
move uses the second mode if 'after == True' and the target is not
1225
versioned but present in the working tree.
1227
move uses the second mode if 'after == False' and the source is
1228
versioned but no longer in the working tree, and the target is not
1229
versioned but present in the working tree.
1231
move uses the first mode if 'after == False' and the source is
1232
versioned and present in the working tree, and the target is not
1233
versioned and not present in the working tree.
1235
Everything else results in an error.
1237
This returns a list of (from_path, to_path) pairs for each
1238
entry that is moved.
1243
# check for deprecated use of signature
1245
to_dir = kwargs.get('to_name', None)
1247
raise TypeError('You must supply a target directory')
1249
symbol_versioning.warn('The parameter to_name was deprecated'
1250
' in version 0.13. Use to_dir instead',
1253
# check destination directory
1254
if isinstance(from_paths, basestring):
1256
inv = self.inventory
1257
to_abs = self.abspath(to_dir)
1258
if not isdir(to_abs):
1259
raise errors.BzrMoveFailedError('',to_dir,
1260
errors.NotADirectory(to_abs))
1261
if not self.has_filename(to_dir):
1262
raise errors.BzrMoveFailedError('',to_dir,
1263
errors.NotInWorkingDirectory(to_dir))
1264
to_dir_id = inv.path2id(to_dir)
1265
if to_dir_id is None:
1266
raise errors.BzrMoveFailedError('',to_dir,
1267
errors.NotVersionedError(path=str(to_dir)))
1269
to_dir_ie = inv[to_dir_id]
1270
if to_dir_ie.kind != 'directory':
1271
raise errors.BzrMoveFailedError('',to_dir,
1272
errors.NotADirectory(to_abs))
1274
# create rename entries and tuples
1275
for from_rel in from_paths:
1276
from_tail = splitpath(from_rel)[-1]
1277
from_id = inv.path2id(from_rel)
1279
raise errors.BzrMoveFailedError(from_rel,to_dir,
1280
errors.NotVersionedError(path=str(from_rel)))
1282
from_entry = inv[from_id]
1283
from_parent_id = from_entry.parent_id
1284
to_rel = pathjoin(to_dir, from_tail)
1285
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1287
from_tail=from_tail,
1288
from_parent_id=from_parent_id,
1289
to_rel=to_rel, to_tail=from_tail,
1290
to_parent_id=to_dir_id)
1291
rename_entries.append(rename_entry)
1292
rename_tuples.append((from_rel, to_rel))
1294
# determine which move mode to use. checks also for movability
1295
rename_entries = self._determine_mv_mode(rename_entries, after)
1297
original_modified = self._inventory_is_modified
1300
self._inventory_is_modified = True
1301
self._move(rename_entries)
1303
# restore the inventory on error
1304
self._inventory_is_modified = original_modified
1306
self._write_inventory(inv)
1307
return rename_tuples
1309
def _determine_mv_mode(self, rename_entries, after=False):
1310
"""Determines for each from-to pair if both inventory and working tree
1311
or only the inventory has to be changed.
1313
Also does basic plausability tests.
1315
inv = self.inventory
1317
for rename_entry in rename_entries:
1318
# store to local variables for easier reference
1319
from_rel = rename_entry.from_rel
1320
from_id = rename_entry.from_id
1321
to_rel = rename_entry.to_rel
1322
to_id = inv.path2id(to_rel)
1323
only_change_inv = False
1325
# check the inventory for source and destination
1327
raise errors.BzrMoveFailedError(from_rel,to_rel,
1328
errors.NotVersionedError(path=str(from_rel)))
1329
if to_id is not None:
1330
raise errors.BzrMoveFailedError(from_rel,to_rel,
1331
errors.AlreadyVersionedError(path=str(to_rel)))
1333
# try to determine the mode for rename (only change inv or change
1334
# inv and file system)
1336
if not self.has_filename(to_rel):
1337
raise errors.BzrMoveFailedError(from_id,to_rel,
1338
errors.NoSuchFile(path=str(to_rel),
1339
extra="New file has not been created yet"))
1340
only_change_inv = True
1341
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1342
only_change_inv = True
1343
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1344
only_change_inv = False
1345
elif (not self.case_sensitive
1346
and from_rel.lower() == to_rel.lower()
1347
and self.has_filename(from_rel)):
1348
only_change_inv = False
1350
# something is wrong, so lets determine what exactly
1351
if not self.has_filename(from_rel) and \
1352
not self.has_filename(to_rel):
1353
raise errors.BzrRenameFailedError(from_rel,to_rel,
1354
errors.PathsDoNotExist(paths=(str(from_rel),
1357
raise errors.RenameFailedFilesExist(from_rel, to_rel)
1358
rename_entry.only_change_inv = only_change_inv
1359
return rename_entries
1361
def _move(self, rename_entries):
1362
"""Moves a list of files.
1364
Depending on the value of the flag 'only_change_inv', the
1365
file will be moved on the file system or not.
1367
inv = self.inventory
1370
for entry in rename_entries:
1372
self._move_entry(entry)
1374
self._rollback_move(moved)
1378
def _rollback_move(self, moved):
1379
"""Try to rollback a previous move in case of an filesystem error."""
1380
inv = self.inventory
1383
self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1384
entry.to_tail, entry.to_parent_id, entry.from_rel,
1385
entry.from_tail, entry.from_parent_id,
1386
entry.only_change_inv))
1387
except errors.BzrMoveFailedError, e:
1388
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1389
" The working tree is in an inconsistent state."
1390
" Please consider doing a 'bzr revert'."
1391
" Error message is: %s" % e)
1393
def _move_entry(self, entry):
1394
inv = self.inventory
1395
from_rel_abs = self.abspath(entry.from_rel)
1396
to_rel_abs = self.abspath(entry.to_rel)
1397
if from_rel_abs == to_rel_abs:
1398
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1399
"Source and target are identical.")
1401
if not entry.only_change_inv:
1403
osutils.rename(from_rel_abs, to_rel_abs)
1405
raise errors.BzrMoveFailedError(entry.from_rel,
1407
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1409
@needs_tree_write_lock
1410
def rename_one(self, from_rel, to_rel, after=False):
1413
This can change the directory or the filename or both.
1415
rename_one has several 'modes' to work. First, it can rename a physical
1416
file and change the file_id. That is the normal mode. Second, it can
1417
only change the file_id without touching any physical file. This is
1418
the new mode introduced in version 0.15.
1420
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1421
versioned but present in the working tree.
1423
rename_one uses the second mode if 'after == False' and 'from_rel' is
1424
versioned but no longer in the working tree, and 'to_rel' is not
1425
versioned but present in the working tree.
1427
rename_one uses the first mode if 'after == False' and 'from_rel' is
1428
versioned and present in the working tree, and 'to_rel' is not
1429
versioned and not present in the working tree.
1431
Everything else results in an error.
1433
inv = self.inventory
1436
# create rename entries and tuples
1437
from_tail = splitpath(from_rel)[-1]
1438
from_id = inv.path2id(from_rel)
1440
raise errors.BzrRenameFailedError(from_rel,to_rel,
1441
errors.NotVersionedError(path=str(from_rel)))
1442
from_entry = inv[from_id]
1443
from_parent_id = from_entry.parent_id
1444
to_dir, to_tail = os.path.split(to_rel)
1445
to_dir_id = inv.path2id(to_dir)
1446
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1448
from_tail=from_tail,
1449
from_parent_id=from_parent_id,
1450
to_rel=to_rel, to_tail=to_tail,
1451
to_parent_id=to_dir_id)
1452
rename_entries.append(rename_entry)
1454
# determine which move mode to use. checks also for movability
1455
rename_entries = self._determine_mv_mode(rename_entries, after)
1457
# check if the target changed directory and if the target directory is
1459
if to_dir_id is None:
1460
raise errors.BzrMoveFailedError(from_rel,to_rel,
1461
errors.NotVersionedError(path=str(to_dir)))
1463
# all checks done. now we can continue with our actual work
1464
mutter('rename_one:\n'
1469
' to_dir_id {%s}\n',
1470
from_id, from_rel, to_rel, to_dir, to_dir_id)
1472
self._move(rename_entries)
1473
self._write_inventory(inv)
1475
class _RenameEntry(object):
1476
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1477
to_rel, to_tail, to_parent_id, only_change_inv=False):
1478
self.from_rel = from_rel
1479
self.from_id = from_id
1480
self.from_tail = from_tail
1481
self.from_parent_id = from_parent_id
1482
self.to_rel = to_rel
1483
self.to_tail = to_tail
1484
self.to_parent_id = to_parent_id
1485
self.only_change_inv = only_change_inv
1489
"""Return all unknown files.
1491
These are files in the working directory that are not versioned or
1492
control files or ignored.
1494
# force the extras method to be fully executed before returning, to
1495
# prevent race conditions with the lock
1497
[subp for subp in self.extras() if not self.is_ignored(subp)])
1499
@needs_tree_write_lock
1500
def unversion(self, file_ids):
1501
"""Remove the file ids in file_ids from the current versioned set.
1503
When a file_id is unversioned, all of its children are automatically
1506
:param file_ids: The file ids to stop versioning.
1507
:raises: NoSuchId if any fileid is not currently versioned.
1509
for file_id in file_ids:
1510
if self._inventory.has_id(file_id):
1511
self._inventory.remove_recursive_id(file_id)
1513
raise errors.NoSuchId(self, file_id)
1515
# in the future this should just set a dirty bit to wait for the
1516
# final unlock. However, until all methods of workingtree start
1517
# with the current in -memory inventory rather than triggering
1518
# a read, it is more complex - we need to teach read_inventory
1519
# to know when to read, and when to not read first... and possibly
1520
# to save first when the in memory one may be corrupted.
1521
# so for now, we just only write it if it is indeed dirty.
1523
self._write_inventory(self._inventory)
1525
def _iter_conflicts(self):
1527
for info in self.list_files():
1529
stem = get_conflicted_stem(path)
1532
if stem not in conflicted:
1533
conflicted.add(stem)
1537
def pull(self, source, overwrite=False, stop_revision=None,
1538
change_reporter=None, possible_transports=None):
1539
top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1542
pp = ProgressPhase("Pull phase", 2, top_pb)
1544
old_revision_info = self.branch.last_revision_info()
1545
basis_tree = self.basis_tree()
1546
count = self.branch.pull(source, overwrite, stop_revision,
1547
possible_transports=possible_transports)
1548
new_revision_info = self.branch.last_revision_info()
1549
if new_revision_info != old_revision_info:
1551
repository = self.branch.repository
1552
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1553
basis_tree.lock_read()
1555
new_basis_tree = self.branch.basis_tree()
1562
change_reporter=change_reporter)
1563
if (basis_tree.inventory.root is None and
1564
new_basis_tree.inventory.root is not None):
1565
self.set_root_id(new_basis_tree.get_root_id())
1569
# TODO - dedup parents list with things merged by pull ?
1570
# reuse the revisiontree we merged against to set the new
1572
parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1573
# we have to pull the merge trees out again, because
1574
# merge_inner has set the ids. - this corner is not yet
1575
# layered well enough to prevent double handling.
1576
# XXX TODO: Fix the double handling: telling the tree about
1577
# the already known parent data is wasteful.
1578
merges = self.get_parent_ids()[1:]
1579
parent_trees.extend([
1580
(parent, repository.revision_tree(parent)) for
1582
self.set_parent_trees(parent_trees)
1589
def put_file_bytes_non_atomic(self, file_id, bytes):
1590
"""See MutableTree.put_file_bytes_non_atomic."""
1591
stream = file(self.id2abspath(file_id), 'wb')
1596
# TODO: update the hashcache here ?
1599
"""Yield all unversioned files in this WorkingTree.
1601
If there are any unversioned directories then only the directory is
1602
returned, not all its children. But if there are unversioned files
1603
under a versioned subdirectory, they are returned.
1605
Currently returned depth-first, sorted by name within directories.
1606
This is the same order used by 'osutils.walkdirs'.
1608
## TODO: Work from given directory downwards
1609
for path, dir_entry in self.inventory.directories():
1610
# mutter("search for unknowns in %r", path)
1611
dirabs = self.abspath(path)
1612
if not isdir(dirabs):
1613
# e.g. directory deleted
1617
for subf in os.listdir(dirabs):
1620
if subf not in dir_entry.children:
1623
can_access) = osutils.normalized_filename(subf)
1624
except UnicodeDecodeError:
1625
path_os_enc = path.encode(osutils._fs_enc)
1626
relpath = path_os_enc + '/' + subf
1627
raise errors.BadFilenameEncoding(relpath,
1629
if subf_norm != subf and can_access:
1630
if subf_norm not in dir_entry.children:
1631
fl.append(subf_norm)
1637
subp = pathjoin(path, subf)
1640
def ignored_files(self):
1641
"""Yield list of PATH, IGNORE_PATTERN"""
1642
for subp in self.extras():
1643
pat = self.is_ignored(subp)
1647
def get_ignore_list(self):
1648
"""Return list of ignore patterns.
1650
Cached in the Tree object after the first call.
1652
ignoreset = getattr(self, '_ignoreset', None)
1653
if ignoreset is not None:
1656
ignore_globs = set()
1657
ignore_globs.update(ignores.get_runtime_ignores())
1658
ignore_globs.update(ignores.get_user_ignores())
1659
if self.has_filename(bzrlib.IGNORE_FILENAME):
1660
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1662
ignore_globs.update(ignores.parse_ignore_file(f))
1665
self._ignoreset = ignore_globs
1668
def _flush_ignore_list_cache(self):
1669
"""Resets the cached ignore list to force a cache rebuild."""
1670
self._ignoreset = None
1671
self._ignoreglobster = None
1673
def is_ignored(self, filename):
1674
r"""Check whether the filename matches an ignore pattern.
1676
Patterns containing '/' or '\' need to match the whole path;
1677
others match against only the last component.
1679
If the file is ignored, returns the pattern which caused it to
1680
be ignored, otherwise None. So this can simply be used as a
1681
boolean if desired."""
1682
if getattr(self, '_ignoreglobster', None) is None:
1683
self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1684
return self._ignoreglobster.match(filename)
1686
def kind(self, file_id):
1687
return file_kind(self.id2abspath(file_id))
1689
def stored_kind(self, file_id):
1690
"""See Tree.stored_kind"""
1691
return self.inventory[file_id].kind
1693
def _comparison_data(self, entry, path):
1694
abspath = self.abspath(path)
1696
stat_value = os.lstat(abspath)
1698
if getattr(e, 'errno', None) == errno.ENOENT:
1705
mode = stat_value.st_mode
1706
kind = osutils.file_kind_from_stat_mode(mode)
1707
if not supports_executable():
1708
executable = entry is not None and entry.executable
1710
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1711
return kind, executable, stat_value
1713
def _file_size(self, entry, stat_value):
1714
return stat_value.st_size
1716
def last_revision(self):
1717
"""Return the last revision of the branch for this tree.
1719
This format tree does not support a separate marker for last-revision
1720
compared to the branch.
1722
See MutableTree.last_revision
1724
return self._last_revision()
1727
def _last_revision(self):
1728
"""helper for get_parent_ids."""
1729
return _mod_revision.ensure_null(self.branch.last_revision())
1731
def is_locked(self):
1732
return self._control_files.is_locked()
1734
def _must_be_locked(self):
1735
if not self.is_locked():
1736
raise errors.ObjectNotLocked(self)
1738
def lock_read(self):
1739
"""See Branch.lock_read, and WorkingTree.unlock."""
1740
if not self.is_locked():
1742
self.branch.lock_read()
1744
return self._control_files.lock_read()
1746
self.branch.unlock()
1749
def lock_tree_write(self):
1750
"""See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1751
if not self.is_locked():
1753
self.branch.lock_read()
1755
return self._control_files.lock_write()
1757
self.branch.unlock()
1760
def lock_write(self):
1761
"""See MutableTree.lock_write, and WorkingTree.unlock."""
1762
if not self.is_locked():
1764
self.branch.lock_write()
1766
return self._control_files.lock_write()
1768
self.branch.unlock()
1771
def get_physical_lock_status(self):
1772
return self._control_files.get_physical_lock_status()
1774
def _basis_inventory_name(self):
1775
return 'basis-inventory-cache'
1777
def _reset_data(self):
1778
"""Reset transient data that cannot be revalidated."""
1779
self._inventory_is_modified = False
1780
result = self._deserialize(self._transport.get('inventory'))
1781
self._set_inventory(result, dirty=False)
1783
@needs_tree_write_lock
1784
def set_last_revision(self, new_revision):
1785
"""Change the last revision in the working tree."""
1786
if self._change_last_revision(new_revision):
1787
self._cache_basis_inventory(new_revision)
1789
def _change_last_revision(self, new_revision):
1790
"""Template method part of set_last_revision to perform the change.
1792
This is used to allow WorkingTree3 instances to not affect branch
1793
when their last revision is set.
1795
if _mod_revision.is_null(new_revision):
1796
self.branch.set_revision_history([])
1799
self.branch.generate_revision_history(new_revision)
1800
except errors.NoSuchRevision:
1801
# not present in the repo - dont try to set it deeper than the tip
1802
self.branch.set_revision_history([new_revision])
1805
def _write_basis_inventory(self, xml):
1806
"""Write the basis inventory XML to the basis-inventory file"""
1807
path = self._basis_inventory_name()
1809
self._transport.put_file(path, sio,
1810
mode=self._control_files._file_mode)
1812
def _create_basis_xml_from_inventory(self, revision_id, inventory):
1813
"""Create the text that will be saved in basis-inventory"""
1814
inventory.revision_id = revision_id
1815
return xml7.serializer_v7.write_inventory_to_string(inventory)
1817
def _cache_basis_inventory(self, new_revision):
1818
"""Cache new_revision as the basis inventory."""
1819
# TODO: this should allow the ready-to-use inventory to be passed in,
1820
# as commit already has that ready-to-use [while the format is the
1823
# this double handles the inventory - unpack and repack -
1824
# but is easier to understand. We can/should put a conditional
1825
# in here based on whether the inventory is in the latest format
1826
# - perhaps we should repack all inventories on a repository
1828
# the fast path is to copy the raw xml from the repository. If the
1829
# xml contains 'revision_id="', then we assume the right
1830
# revision_id is set. We must check for this full string, because a
1831
# root node id can legitimately look like 'revision_id' but cannot
1833
xml = self.branch.repository.get_inventory_xml(new_revision)
1834
firstline = xml.split('\n', 1)[0]
1835
if (not 'revision_id="' in firstline or
1836
'format="7"' not in firstline):
1837
inv = self.branch.repository.deserialise_inventory(
1839
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1840
self._write_basis_inventory(xml)
1841
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1844
def read_basis_inventory(self):
1845
"""Read the cached basis inventory."""
1846
path = self._basis_inventory_name()
1847
return self._transport.get_bytes(path)
1850
def read_working_inventory(self):
1851
"""Read the working inventory.
1853
:raises errors.InventoryModified: read_working_inventory will fail
1854
when the current in memory inventory has been modified.
1856
# conceptually this should be an implementation detail of the tree.
1857
# XXX: Deprecate this.
1858
# ElementTree does its own conversion from UTF-8, so open in
1860
if self._inventory_is_modified:
1861
raise errors.InventoryModified(self)
1862
result = self._deserialize(self._transport.get('inventory'))
1863
self._set_inventory(result, dirty=False)
1866
@needs_tree_write_lock
1867
def remove(self, files, verbose=False, to_file=None, keep_files=True,
1869
"""Remove nominated files from the working inventory.
1871
:files: File paths relative to the basedir.
1872
:keep_files: If true, the files will also be kept.
1873
:force: Delete files and directories, even if they are changed and
1874
even if the directories are not empty.
1876
if isinstance(files, basestring):
1882
unknown_nested_files=set()
1884
def recurse_directory_to_add_files(directory):
1885
# Recurse directory and add all files
1886
# so we can check if they have changed.
1887
for parent_info, file_infos in\
1888
self.walkdirs(directory):
1889
for relpath, basename, kind, lstat, fileid, kind in file_infos:
1890
# Is it versioned or ignored?
1891
if self.path2id(relpath) or self.is_ignored(relpath):
1892
# Add nested content for deletion.
1893
new_files.add(relpath)
1895
# Files which are not versioned and not ignored
1896
# should be treated as unknown.
1897
unknown_nested_files.add((relpath, None, kind))
1899
for filename in files:
1900
# Get file name into canonical form.
1901
abspath = self.abspath(filename)
1902
filename = self.relpath(abspath)
1903
if len(filename) > 0:
1904
new_files.add(filename)
1905
recurse_directory_to_add_files(filename)
1907
files = list(new_files)
1910
return # nothing to do
1912
# Sort needed to first handle directory content before the directory
1913
files.sort(reverse=True)
1915
# Bail out if we are going to delete files we shouldn't
1916
if not keep_files and not force:
1917
has_changed_files = len(unknown_nested_files) > 0
1918
if not has_changed_files:
1919
for (file_id, path, content_change, versioned, parent_id, name,
1920
kind, executable) in self.iter_changes(self.basis_tree(),
1921
include_unchanged=True, require_versioned=False,
1922
want_unversioned=True, specific_files=files):
1923
if versioned == (False, False):
1924
# The record is unknown ...
1925
if not self.is_ignored(path[1]):
1926
# ... but not ignored
1927
has_changed_files = True
1929
elif content_change and (kind[1] is not None):
1930
# Versioned and changed, but not deleted
1931
has_changed_files = True
1934
if has_changed_files:
1935
# Make delta show ALL applicable changes in error message.
1936
tree_delta = self.changes_from(self.basis_tree(),
1937
require_versioned=False, want_unversioned=True,
1938
specific_files=files)
1939
for unknown_file in unknown_nested_files:
1940
if unknown_file not in tree_delta.unversioned:
1941
tree_delta.unversioned.extend((unknown_file,))
1942
raise errors.BzrRemoveChangedFilesError(tree_delta)
1944
# Build inv_delta and delete files where applicaple,
1945
# do this before any modifications to inventory.
1947
fid = self.path2id(f)
1950
message = "%s is not versioned." % (f,)
1953
# having removed it, it must be either ignored or unknown
1954
if self.is_ignored(f):
1958
textui.show_status(new_status, self.kind(fid), f,
1961
inv_delta.append((f, None, fid, None))
1962
message = "removed %s" % (f,)
1965
abs_path = self.abspath(f)
1966
if osutils.lexists(abs_path):
1967
if (osutils.isdir(abs_path) and
1968
len(os.listdir(abs_path)) > 0):
1970
osutils.rmtree(abs_path)
1972
message = "%s is not an empty directory "\
1973
"and won't be deleted." % (f,)
1975
osutils.delete_any(abs_path)
1976
message = "deleted %s" % (f,)
1977
elif message is not None:
1978
# Only care if we haven't done anything yet.
1979
message = "%s does not exist." % (f,)
1981
# Print only one message (if any) per file.
1982
if message is not None:
1984
self.apply_inventory_delta(inv_delta)
1986
@needs_tree_write_lock
1987
def revert(self, filenames=None, old_tree=None, backups=True,
1988
pb=DummyProgress(), report_changes=False):
1989
from bzrlib.conflicts import resolve
1992
symbol_versioning.warn('Using [] to revert all files is deprecated'
1993
' as of bzr 0.91. Please use None (the default) instead.',
1994
DeprecationWarning, stacklevel=2)
1995
if old_tree is None:
1996
basis_tree = self.basis_tree()
1997
basis_tree.lock_read()
1998
old_tree = basis_tree
2002
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
2004
if filenames is None and len(self.get_parent_ids()) > 1:
2006
last_revision = self.last_revision()
2007
if last_revision != NULL_REVISION:
2008
if basis_tree is None:
2009
basis_tree = self.basis_tree()
2010
basis_tree.lock_read()
2011
parent_trees.append((last_revision, basis_tree))
2012
self.set_parent_trees(parent_trees)
2015
resolve(self, filenames, ignore_misses=True, recursive=True)
2017
if basis_tree is not None:
2021
def revision_tree(self, revision_id):
2022
"""See Tree.revision_tree.
2024
WorkingTree can supply revision_trees for the basis revision only
2025
because there is only one cached inventory in the bzr directory.
2027
if revision_id == self.last_revision():
2029
xml = self.read_basis_inventory()
2030
except errors.NoSuchFile:
2034
inv = xml7.serializer_v7.read_inventory_from_string(xml)
2035
# dont use the repository revision_tree api because we want
2036
# to supply the inventory.
2037
if inv.revision_id == revision_id:
2038
return revisiontree.RevisionTree(self.branch.repository,
2040
except errors.BadInventoryFormat:
2042
# raise if there was no inventory, or if we read the wrong inventory.
2043
raise errors.NoSuchRevisionInTree(self, revision_id)
2045
# XXX: This method should be deprecated in favour of taking in a proper
2046
# new Inventory object.
2047
@needs_tree_write_lock
2048
def set_inventory(self, new_inventory_list):
2049
from bzrlib.inventory import (Inventory,
2054
inv = Inventory(self.get_root_id())
2055
for path, file_id, parent, kind in new_inventory_list:
2056
name = os.path.basename(path)
2059
# fixme, there should be a factory function inv,add_??
2060
if kind == 'directory':
2061
inv.add(InventoryDirectory(file_id, name, parent))
2062
elif kind == 'file':
2063
inv.add(InventoryFile(file_id, name, parent))
2064
elif kind == 'symlink':
2065
inv.add(InventoryLink(file_id, name, parent))
2067
raise errors.BzrError("unknown kind %r" % kind)
2068
self._write_inventory(inv)
2070
@needs_tree_write_lock
2071
def set_root_id(self, file_id):
2072
"""Set the root id for this tree."""
2076
'WorkingTree.set_root_id with fileid=None')
2077
file_id = osutils.safe_file_id(file_id)
2078
self._set_root_id(file_id)
2080
def _set_root_id(self, file_id):
2081
"""Set the root id for this tree, in a format specific manner.
2083
:param file_id: The file id to assign to the root. It must not be
2084
present in the current inventory or an error will occur. It must
2085
not be None, but rather a valid file id.
2087
inv = self._inventory
2088
orig_root_id = inv.root.file_id
2089
# TODO: it might be nice to exit early if there was nothing
2090
# to do, saving us from trigger a sync on unlock.
2091
self._inventory_is_modified = True
2092
# we preserve the root inventory entry object, but
2093
# unlinkit from the byid index
2094
del inv._byid[inv.root.file_id]
2095
inv.root.file_id = file_id
2096
# and link it into the index with the new changed id.
2097
inv._byid[inv.root.file_id] = inv.root
2098
# and finally update all children to reference the new id.
2099
# XXX: this should be safe to just look at the root.children
2100
# list, not the WHOLE INVENTORY.
2103
if entry.parent_id == orig_root_id:
2104
entry.parent_id = inv.root.file_id
2107
"""See Branch.unlock.
2109
WorkingTree locking just uses the Branch locking facilities.
2110
This is current because all working trees have an embedded branch
2111
within them. IF in the future, we were to make branch data shareable
2112
between multiple working trees, i.e. via shared storage, then we
2113
would probably want to lock both the local tree, and the branch.
2115
raise NotImplementedError(self.unlock)
2117
def update(self, change_reporter=None, possible_transports=None):
2118
"""Update a working tree along its branch.
2120
This will update the branch if its bound too, which means we have
2121
multiple trees involved:
2123
- The new basis tree of the master.
2124
- The old basis tree of the branch.
2125
- The old basis tree of the working tree.
2126
- The current working tree state.
2128
Pathologically, all three may be different, and non-ancestors of each
2129
other. Conceptually we want to:
2131
- Preserve the wt.basis->wt.state changes
2132
- Transform the wt.basis to the new master basis.
2133
- Apply a merge of the old branch basis to get any 'local' changes from
2135
- Restore the wt.basis->wt.state changes.
2137
There isn't a single operation at the moment to do that, so we:
2138
- Merge current state -> basis tree of the master w.r.t. the old tree
2140
- Do a 'normal' merge of the old branch basis if it is relevant.
2142
if self.branch.get_bound_location() is not None:
2144
update_branch = True
2146
self.lock_tree_write()
2147
update_branch = False
2150
old_tip = self.branch.update(possible_transports)
2153
return self._update_tree(old_tip, change_reporter)
2157
@needs_tree_write_lock
2158
def _update_tree(self, old_tip=None, change_reporter=None):
2159
"""Update a tree to the master branch.
2161
:param old_tip: if supplied, the previous tip revision the branch,
2162
before it was changed to the master branch's tip.
2164
# here if old_tip is not None, it is the old tip of the branch before
2165
# it was updated from the master branch. This should become a pending
2166
# merge in the working tree to preserve the user existing work. we
2167
# cant set that until we update the working trees last revision to be
2168
# one from the new branch, because it will just get absorbed by the
2169
# parent de-duplication logic.
2171
# We MUST save it even if an error occurs, because otherwise the users
2172
# local work is unreferenced and will appear to have been lost.
2176
last_rev = self.get_parent_ids()[0]
2178
last_rev = _mod_revision.NULL_REVISION
2179
if last_rev != _mod_revision.ensure_null(self.branch.last_revision()):
2180
# merge tree state up to new branch tip.
2181
basis = self.basis_tree()
2184
to_tree = self.branch.basis_tree()
2185
if basis.inventory.root is None:
2186
self.set_root_id(to_tree.get_root_id())
2188
result += merge.merge_inner(
2193
change_reporter=change_reporter)
2196
# TODO - dedup parents list with things merged by pull ?
2197
# reuse the tree we've updated to to set the basis:
2198
parent_trees = [(self.branch.last_revision(), to_tree)]
2199
merges = self.get_parent_ids()[1:]
2200
# Ideally we ask the tree for the trees here, that way the working
2201
# tree can decide whether to give us teh entire tree or give us a
2202
# lazy initialised tree. dirstate for instance will have the trees
2203
# in ram already, whereas a last-revision + basis-inventory tree
2204
# will not, but also does not need them when setting parents.
2205
for parent in merges:
2206
parent_trees.append(
2207
(parent, self.branch.repository.revision_tree(parent)))
2208
if (old_tip is not None and not _mod_revision.is_null(old_tip)):
2209
parent_trees.append(
2210
(old_tip, self.branch.repository.revision_tree(old_tip)))
2211
self.set_parent_trees(parent_trees)
2212
last_rev = parent_trees[0][0]
2214
# the working tree had the same last-revision as the master
2215
# branch did. We may still have pivot local work from the local
2216
# branch into old_tip:
2217
if (old_tip is not None and not _mod_revision.is_null(old_tip)):
2218
self.add_parent_tree_id(old_tip)
2219
if (old_tip is not None and not _mod_revision.is_null(old_tip)
2220
and old_tip != last_rev):
2221
# our last revision was not the prior branch last revision
2222
# and we have converted that last revision to a pending merge.
2223
# base is somewhere between the branch tip now
2224
# and the now pending merge
2226
# Since we just modified the working tree and inventory, flush out
2227
# the current state, before we modify it again.
2228
# TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
2229
# requires it only because TreeTransform directly munges the
2230
# inventory and calls tree._write_inventory(). Ultimately we
2231
# should be able to remove this extra flush.
2233
graph = self.branch.repository.get_graph()
2234
base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
2236
base_tree = self.branch.repository.revision_tree(base_rev_id)
2237
other_tree = self.branch.repository.revision_tree(old_tip)
2238
result += merge.merge_inner(
2243
change_reporter=change_reporter)
2246
def _write_hashcache_if_dirty(self):
2247
"""Write out the hashcache if it is dirty."""
2248
if self._hashcache.needs_write:
2250
self._hashcache.write()
2252
if e.errno not in (errno.EPERM, errno.EACCES):
2254
# TODO: jam 20061219 Should this be a warning? A single line
2255
# warning might be sufficient to let the user know what
2257
mutter('Could not write hashcache for %s\nError: %s',
2258
self._hashcache.cache_file_name(), e)
2260
@needs_tree_write_lock
2261
def _write_inventory(self, inv):
2262
"""Write inventory as the current inventory."""
2263
self._set_inventory(inv, dirty=True)
2266
def set_conflicts(self, arg):
2267
raise errors.UnsupportedOperation(self.set_conflicts, self)
2269
def add_conflicts(self, arg):
2270
raise errors.UnsupportedOperation(self.add_conflicts, self)
2273
def conflicts(self):
2274
conflicts = _mod_conflicts.ConflictList()
2275
for conflicted in self._iter_conflicts():
2278
if file_kind(self.abspath(conflicted)) != "file":
2280
except errors.NoSuchFile:
2283
for suffix in ('.THIS', '.OTHER'):
2285
kind = file_kind(self.abspath(conflicted+suffix))
2288
except errors.NoSuchFile:
2292
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
2293
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
2295
file_id=self.path2id(conflicted)))
2298
def walkdirs(self, prefix=""):
2299
"""Walk the directories of this tree.
2301
returns a generator which yields items in the form:
2302
((curren_directory_path, fileid),
2303
[(file1_path, file1_name, file1_kind, (lstat), file1_id,
2306
This API returns a generator, which is only valid during the current
2307
tree transaction - within a single lock_read or lock_write duration.
2309
If the tree is not locked, it may cause an error to be raised,
2310
depending on the tree implementation.
2312
disk_top = self.abspath(prefix)
2313
if disk_top.endswith('/'):
2314
disk_top = disk_top[:-1]
2315
top_strip_len = len(disk_top) + 1
2316
inventory_iterator = self._walkdirs(prefix)
2317
disk_iterator = osutils.walkdirs(disk_top, prefix)
2319
current_disk = disk_iterator.next()
2320
disk_finished = False
2322
if not (e.errno == errno.ENOENT or
2323
(sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
2326
disk_finished = True
2328
current_inv = inventory_iterator.next()
2329
inv_finished = False
2330
except StopIteration:
2333
while not inv_finished or not disk_finished:
2335
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2336
cur_disk_dir_content) = current_disk
2338
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2339
cur_disk_dir_content) = ((None, None), None)
2340
if not disk_finished:
2341
# strip out .bzr dirs
2342
if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
2343
len(cur_disk_dir_content) > 0):
2344
# osutils.walkdirs can be made nicer -
2345
# yield the path-from-prefix rather than the pathjoined
2347
bzrdir_loc = bisect_left(cur_disk_dir_content,
2349
if (bzrdir_loc < len(cur_disk_dir_content)
2350
and cur_disk_dir_content[bzrdir_loc][0] == '.bzr'):
2351
# we dont yield the contents of, or, .bzr itself.
2352
del cur_disk_dir_content[bzrdir_loc]
2354
# everything is unknown
2357
# everything is missing
2360
direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
2362
# disk is before inventory - unknown
2363
dirblock = [(relpath, basename, kind, stat, None, None) for
2364
relpath, basename, kind, stat, top_path in
2365
cur_disk_dir_content]
2366
yield (cur_disk_dir_relpath, None), dirblock
2368
current_disk = disk_iterator.next()
2369
except StopIteration:
2370
disk_finished = True
2372
# inventory is before disk - missing.
2373
dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2374
for relpath, basename, dkind, stat, fileid, kind in
2376
yield (current_inv[0][0], current_inv[0][1]), dirblock
2378
current_inv = inventory_iterator.next()
2379
except StopIteration:
2382
# versioned present directory
2383
# merge the inventory and disk data together
2385
for relpath, subiterator in itertools.groupby(sorted(
2386
current_inv[1] + cur_disk_dir_content,
2387
key=operator.itemgetter(0)), operator.itemgetter(1)):
2388
path_elements = list(subiterator)
2389
if len(path_elements) == 2:
2390
inv_row, disk_row = path_elements
2391
# versioned, present file
2392
dirblock.append((inv_row[0],
2393
inv_row[1], disk_row[2],
2394
disk_row[3], inv_row[4],
2396
elif len(path_elements[0]) == 5:
2398
dirblock.append((path_elements[0][0],
2399
path_elements[0][1], path_elements[0][2],
2400
path_elements[0][3], None, None))
2401
elif len(path_elements[0]) == 6:
2402
# versioned, absent file.
2403
dirblock.append((path_elements[0][0],
2404
path_elements[0][1], 'unknown', None,
2405
path_elements[0][4], path_elements[0][5]))
2407
raise NotImplementedError('unreachable code')
2408
yield current_inv[0], dirblock
2410
current_inv = inventory_iterator.next()
2411
except StopIteration:
2414
current_disk = disk_iterator.next()
2415
except StopIteration:
2416
disk_finished = True
2418
def _walkdirs(self, prefix=""):
2419
"""Walk the directories of this tree.
2421
:prefix: is used as the directrory to start with.
2422
returns a generator which yields items in the form:
2423
((curren_directory_path, fileid),
2424
[(file1_path, file1_name, file1_kind, None, file1_id,
2427
_directory = 'directory'
2428
# get the root in the inventory
2429
inv = self.inventory
2430
top_id = inv.path2id(prefix)
2434
pending = [(prefix, '', _directory, None, top_id, None)]
2437
currentdir = pending.pop()
2438
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2439
top_id = currentdir[4]
2441
relroot = currentdir[0] + '/'
2444
# FIXME: stash the node in pending
2446
if entry.kind == 'directory':
2447
for name, child in entry.sorted_children():
2448
dirblock.append((relroot + name, name, child.kind, None,
2449
child.file_id, child.kind
2451
yield (currentdir[0], entry.file_id), dirblock
2452
# push the user specified dirs from dirblock
2453
for dir in reversed(dirblock):
2454
if dir[2] == _directory:
2457
@needs_tree_write_lock
2458
def auto_resolve(self):
2459
"""Automatically resolve text conflicts according to contents.
2461
Only text conflicts are auto_resolvable. Files with no conflict markers
2462
are considered 'resolved', because bzr always puts conflict markers
2463
into files that have text conflicts. The corresponding .THIS .BASE and
2464
.OTHER files are deleted, as per 'resolve'.
2465
:return: a tuple of ConflictLists: (un_resolved, resolved).
2467
un_resolved = _mod_conflicts.ConflictList()
2468
resolved = _mod_conflicts.ConflictList()
2469
conflict_re = re.compile('^(<{7}|={7}|>{7})')
2470
for conflict in self.conflicts():
2471
if (conflict.typestring != 'text conflict' or
2472
self.kind(conflict.file_id) != 'file'):
2473
un_resolved.append(conflict)
2475
my_file = open(self.id2abspath(conflict.file_id), 'rb')
2477
for line in my_file:
2478
if conflict_re.search(line):
2479
un_resolved.append(conflict)
2482
resolved.append(conflict)
2485
resolved.remove_files(self)
2486
self.set_conflicts(un_resolved)
2487
return un_resolved, resolved
2491
tree_basis = self.basis_tree()
2492
tree_basis.lock_read()
2494
repo_basis = self.branch.repository.revision_tree(
2495
self.last_revision())
2496
if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2497
raise errors.BzrCheckError(
2498
"Mismatched basis inventory content.")
2503
def _validate(self):
2504
"""Validate internal structures.
2506
This is meant mostly for the test suite. To give it a chance to detect
2507
corruption after actions have occurred. The default implementation is a
2510
:return: None. An exception should be raised if there is an error.
2515
def _get_rules_searcher(self, default_searcher):
2516
"""See Tree._get_rules_searcher."""
2517
if self._rules_searcher is None:
2518
self._rules_searcher = super(WorkingTree,
2519
self)._get_rules_searcher(default_searcher)
2520
return self._rules_searcher
2522
def get_shelf_manager(self):
2523
"""Return the ShelfManager for this WorkingTree."""
2524
from bzrlib.shelf import ShelfManager
2525
return ShelfManager(self, self._transport)
2528
class WorkingTree2(WorkingTree):
2529
"""This is the Format 2 working tree.
2531
This was the first weave based working tree.
2532
- uses os locks for locking.
2533
- uses the branch last-revision.
2536
def __init__(self, *args, **kwargs):
2537
super(WorkingTree2, self).__init__(*args, **kwargs)
2538
# WorkingTree2 has more of a constraint that self._inventory must
2539
# exist. Because this is an older format, we don't mind the overhead
2540
# caused by the extra computation here.
2542
# Newer WorkingTree's should only have self._inventory set when they
2544
if self._inventory is None:
2545
self.read_working_inventory()
2547
def lock_tree_write(self):
2548
"""See WorkingTree.lock_tree_write().
2550
In Format2 WorkingTrees we have a single lock for the branch and tree
2551
so lock_tree_write() degrades to lock_write().
2553
self.branch.lock_write()
2555
return self._control_files.lock_write()
2557
self.branch.unlock()
2561
# do non-implementation specific cleanup
2564
# we share control files:
2565
if self._control_files._lock_count == 3:
2566
# _inventory_is_modified is always False during a read lock.
2567
if self._inventory_is_modified:
2569
self._write_hashcache_if_dirty()
2571
# reverse order of locking.
2573
return self._control_files.unlock()
2575
self.branch.unlock()
2578
class WorkingTree3(WorkingTree):
2579
"""This is the Format 3 working tree.
2581
This differs from the base WorkingTree by:
2582
- having its own file lock
2583
- having its own last-revision property.
2585
This is new in bzr 0.8
2589
def _last_revision(self):
2590
"""See Mutable.last_revision."""
2592
return self._transport.get_bytes('last-revision')
2593
except errors.NoSuchFile:
2594
return _mod_revision.NULL_REVISION
2596
def _change_last_revision(self, revision_id):
2597
"""See WorkingTree._change_last_revision."""
2598
if revision_id is None or revision_id == NULL_REVISION:
2600
self._transport.delete('last-revision')
2601
except errors.NoSuchFile:
2605
self._transport.put_bytes('last-revision', revision_id,
2606
mode=self._control_files._file_mode)
2609
@needs_tree_write_lock
2610
def set_conflicts(self, conflicts):
2611
self._put_rio('conflicts', conflicts.to_stanzas(),
2614
@needs_tree_write_lock
2615
def add_conflicts(self, new_conflicts):
2616
conflict_set = set(self.conflicts())
2617
conflict_set.update(set(list(new_conflicts)))
2618
self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2619
key=_mod_conflicts.Conflict.sort_key)))
2622
def conflicts(self):
2624
confile = self._transport.get('conflicts')
2625
except errors.NoSuchFile:
2626
return _mod_conflicts.ConflictList()
2629
if confile.next() != CONFLICT_HEADER_1 + '\n':
2630
raise errors.ConflictFormatError()
2631
except StopIteration:
2632
raise errors.ConflictFormatError()
2633
return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2638
# do non-implementation specific cleanup
2640
if self._control_files._lock_count == 1:
2641
# _inventory_is_modified is always False during a read lock.
2642
if self._inventory_is_modified:
2644
self._write_hashcache_if_dirty()
2645
# reverse order of locking.
2647
return self._control_files.unlock()
2649
self.branch.unlock()
2652
def get_conflicted_stem(path):
2653
for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
2654
if path.endswith(suffix):
2655
return path[:-len(suffix)]
2658
class WorkingTreeFormat(object):
2659
"""An encapsulation of the initialization and open routines for a format.
2661
Formats provide three things:
2662
* An initialization routine,
2666
Formats are placed in an dict by their format string for reference
2667
during workingtree opening. Its not required that these be instances, they
2668
can be classes themselves with class methods - it simply depends on
2669
whether state is needed for a given format or not.
2671
Once a format is deprecated, just deprecate the initialize and open
2672
methods on the format class. Do not deprecate the object, as the
2673
object will be created every time regardless.
2676
_default_format = None
2677
"""The default format used for new trees."""
2680
"""The known formats."""
2682
requires_rich_root = False
2684
upgrade_recommended = False
2687
def find_format(klass, a_bzrdir):
2688
"""Return the format for the working tree object in a_bzrdir."""
2690
transport = a_bzrdir.get_workingtree_transport(None)
2691
format_string = transport.get("format").read()
2692
return klass._formats[format_string]
2693
except errors.NoSuchFile:
2694
raise errors.NoWorkingTree(base=transport.base)
2696
raise errors.UnknownFormatError(format=format_string,
2697
kind="working tree")
2699
def __eq__(self, other):
2700
return self.__class__ is other.__class__
2702
def __ne__(self, other):
2703
return not (self == other)
2706
def get_default_format(klass):
2707
"""Return the current default format."""
2708
return klass._default_format
2710
def get_format_string(self):
2711
"""Return the ASCII format string that identifies this format."""
2712
raise NotImplementedError(self.get_format_string)
2714
def get_format_description(self):
2715
"""Return the short description for this format."""
2716
raise NotImplementedError(self.get_format_description)
2718
def is_supported(self):
2719
"""Is this format supported?
2721
Supported formats can be initialized and opened.
2722
Unsupported formats may not support initialization or committing or
2723
some other features depending on the reason for not being supported.
2727
def supports_views(self):
2728
"""True if this format supports stored views."""
2732
def register_format(klass, format):
2733
klass._formats[format.get_format_string()] = format
2736
def set_default_format(klass, format):
2737
klass._default_format = format
2740
def unregister_format(klass, format):
2741
del klass._formats[format.get_format_string()]
2744
class WorkingTreeFormat2(WorkingTreeFormat):
2745
"""The second working tree format.
2747
This format modified the hash cache from the format 1 hash cache.
2750
upgrade_recommended = True
2752
def get_format_description(self):
2753
"""See WorkingTreeFormat.get_format_description()."""
2754
return "Working tree format 2"
2756
def _stub_initialize_on_transport(self, transport, file_mode):
2757
"""Workaround: create control files for a remote working tree.
2759
This ensures that it can later be updated and dealt with locally,
2760
since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2761
no working tree. (See bug #43064).
2765
xml5.serializer_v5.write_inventory(inv, sio, working=True)
2767
transport.put_file('inventory', sio, file_mode)
2768
transport.put_bytes('pending-merges', '', file_mode)
2770
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2771
accelerator_tree=None, hardlink=False):
2772
"""See WorkingTreeFormat.initialize()."""
2773
if not isinstance(a_bzrdir.transport, LocalTransport):
2774
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2775
if from_branch is not None:
2776
branch = from_branch
2778
branch = a_bzrdir.open_branch()
2779
if revision_id is None:
2780
revision_id = _mod_revision.ensure_null(branch.last_revision())
2783
branch.generate_revision_history(revision_id)
2787
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2793
basis_tree = branch.repository.revision_tree(revision_id)
2794
if basis_tree.inventory.root is not None:
2795
wt.set_root_id(basis_tree.get_root_id())
2796
# set the parent list and cache the basis tree.
2797
if _mod_revision.is_null(revision_id):
2800
parent_trees = [(revision_id, basis_tree)]
2801
wt.set_parent_trees(parent_trees)
2802
transform.build_tree(basis_tree, wt)
2806
super(WorkingTreeFormat2, self).__init__()
2807
self._matchingbzrdir = bzrdir.BzrDirFormat6()
2809
def open(self, a_bzrdir, _found=False):
2810
"""Return the WorkingTree object for a_bzrdir
2812
_found is a private parameter, do not use it. It is used to indicate
2813
if format probing has already been done.
2816
# we are being called directly and must probe.
2817
raise NotImplementedError
2818
if not isinstance(a_bzrdir.transport, LocalTransport):
2819
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2820
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2826
class WorkingTreeFormat3(WorkingTreeFormat):
2827
"""The second working tree format updated to record a format marker.
2830
- exists within a metadir controlling .bzr
2831
- includes an explicit version marker for the workingtree control
2832
files, separate from the BzrDir format
2833
- modifies the hash cache format
2835
- uses a LockDir to guard access for writes.
2838
upgrade_recommended = True
2840
def get_format_string(self):
2841
"""See WorkingTreeFormat.get_format_string()."""
2842
return "Bazaar-NG Working Tree format 3"
2844
def get_format_description(self):
2845
"""See WorkingTreeFormat.get_format_description()."""
2846
return "Working tree format 3"
2848
_lock_file_name = 'lock'
2849
_lock_class = LockDir
2851
_tree_class = WorkingTree3
2853
def __get_matchingbzrdir(self):
2854
return bzrdir.BzrDirMetaFormat1()
2856
_matchingbzrdir = property(__get_matchingbzrdir)
2858
def _open_control_files(self, a_bzrdir):
2859
transport = a_bzrdir.get_workingtree_transport(None)
2860
return LockableFiles(transport, self._lock_file_name,
2863
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2864
accelerator_tree=None, hardlink=False):
2865
"""See WorkingTreeFormat.initialize().
2867
:param revision_id: if supplied, create a working tree at a different
2868
revision than the branch is at.
2869
:param accelerator_tree: A tree which can be used for retrieving file
2870
contents more quickly than the revision tree, i.e. a workingtree.
2871
The revision tree will be used for cases where accelerator_tree's
2872
content is different.
2873
:param hardlink: If true, hard-link files from accelerator_tree,
2876
if not isinstance(a_bzrdir.transport, LocalTransport):
2877
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2878
transport = a_bzrdir.get_workingtree_transport(self)
2879
control_files = self._open_control_files(a_bzrdir)
2880
control_files.create_lock()
2881
control_files.lock_write()
2882
transport.put_bytes('format', self.get_format_string(),
2883
mode=control_files._file_mode)
2884
if from_branch is not None:
2885
branch = from_branch
2887
branch = a_bzrdir.open_branch()
2888
if revision_id is None:
2889
revision_id = _mod_revision.ensure_null(branch.last_revision())
2890
# WorkingTree3 can handle an inventory which has a unique root id.
2891
# as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
2892
# those trees. And because there isn't a format bump inbetween, we
2893
# are maintaining compatibility with older clients.
2894
# inv = Inventory(root_id=gen_root_id())
2895
inv = self._initial_inventory()
2896
wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2902
_control_files=control_files)
2903
wt.lock_tree_write()
2905
basis_tree = branch.repository.revision_tree(revision_id)
2906
# only set an explicit root id if there is one to set.
2907
if basis_tree.inventory.root is not None:
2908
wt.set_root_id(basis_tree.get_root_id())
2909
if revision_id == NULL_REVISION:
2910
wt.set_parent_trees([])
2912
wt.set_parent_trees([(revision_id, basis_tree)])
2913
transform.build_tree(basis_tree, wt)
2915
# Unlock in this order so that the unlock-triggers-flush in
2916
# WorkingTree is given a chance to fire.
2917
control_files.unlock()
2921
def _initial_inventory(self):
2925
super(WorkingTreeFormat3, self).__init__()
2927
def open(self, a_bzrdir, _found=False):
2928
"""Return the WorkingTree object for a_bzrdir
2930
_found is a private parameter, do not use it. It is used to indicate
2931
if format probing has already been done.
2934
# we are being called directly and must probe.
2935
raise NotImplementedError
2936
if not isinstance(a_bzrdir.transport, LocalTransport):
2937
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2938
wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2941
def _open(self, a_bzrdir, control_files):
2942
"""Open the tree itself.
2944
:param a_bzrdir: the dir for the tree.
2945
:param control_files: the control files for the tree.
2947
return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2951
_control_files=control_files)
2954
return self.get_format_string()
2957
__default_format = WorkingTreeFormat4()
2958
WorkingTreeFormat.register_format(__default_format)
2959
WorkingTreeFormat.register_format(workingtree_5.WorkingTreeFormat5())
2960
WorkingTreeFormat.register_format(WorkingTreeFormat3())
2961
WorkingTreeFormat.set_default_format(__default_format)
2962
# formats which have no format string are not discoverable
2963
# and not independently creatable, so are not registered.
2964
_legacy_formats = [WorkingTreeFormat2(),