1
# Copyright (C) 2005-2011 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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.
23
At the moment every WorkingTree has its own branch. Remote
24
WorkingTrees aren't supported.
26
To get a WorkingTree, call controldir.open_workingtree() or
27
WorkingTree.open(dir).
30
from __future__ import absolute_import
39
from .lazy_import import lazy_import
40
lazy_import(globals(), """
45
conflicts as _mod_conflicts,
48
filters as _mod_filters,
51
revision as _mod_revision,
61
from .i18n import gettext
62
from . import mutabletree
63
from .trace import mutter, note
66
ERROR_PATH_NOT_FOUND = 3 # WindowsError errno code, equivalent to ENOENT
69
class SettingFileIdUnsupported(errors.BzrError):
71
_fmt = "This format does not support setting file ids."
74
class ShelvingUnsupported(errors.BzrError):
76
_fmt = "This format does not support shelving changes."
79
class WorkingTree(mutabletree.MutableTree, controldir.ControlComponent):
82
:ivar basedir: The root of the tree on disk. This is a unicode path object
83
(as opposed to a URL).
86
# override this to set the strategy for storing views
87
def _make_views(self):
88
return views.DisabledViews(self)
90
def __init__(self, basedir='.',
96
"""Construct a WorkingTree instance. This is not a public API.
98
:param branch: A branch to override probing for the branch.
100
self._format = _format
101
self.controldir = _controldir
103
raise errors.BzrError("Please use controldir.open_workingtree or "
104
"WorkingTree.open() to obtain a WorkingTree.")
105
basedir = osutils.safe_unicode(basedir)
106
mutter("opening working tree %r", basedir)
107
if branch is not None:
108
self._branch = branch
110
self._branch = self.controldir.open_branch()
111
self.basedir = osutils.realpath(basedir)
112
self._transport = _transport
113
self._rules_searcher = None
114
self.views = self._make_views()
117
def user_transport(self):
118
return self.controldir.user_transport
121
def control_transport(self):
122
return self._transport
124
def is_control_filename(self, filename):
125
"""True if filename is the name of a control file in this tree.
127
:param filename: A filename within the tree. This is a relative path
128
from the root of this tree.
130
This is true IF and ONLY IF the filename is part of the meta data
131
that bzr controls in this tree. I.E. a random .bzr directory placed
132
on disk will not be a control file for this tree.
134
return self.controldir.is_control_filename(filename)
137
fget=lambda self: self._branch,
138
doc="""The branch this WorkingTree is connected to.
140
This cannot be set - it is reflective of the actual disk structure
141
the working tree has been constructed from.
144
def has_versioned_directories(self):
145
"""See `Tree.has_versioned_directories`."""
146
return self._format.supports_versioned_directories
148
def supports_merge_modified(self):
149
"""Indicate whether this workingtree supports storing merge_modified.
151
return self._format.supports_merge_modified
153
def _supports_executable(self):
154
if sys.platform == 'win32':
156
# FIXME: Ideally this should check the file system
159
def break_lock(self):
160
"""Break a lock if one is present from another instance.
162
Uses the ui factory to ask for confirmation if the lock may be from
165
This will probe the repository for its lock as well.
167
raise NotImplementedError(self.break_lock)
169
def requires_rich_root(self):
170
return self._format.requires_rich_root
172
def supports_tree_reference(self):
175
def supports_content_filtering(self):
176
return self._format.supports_content_filtering()
178
def supports_views(self):
179
return self.views.supports_views()
181
def supports_setting_file_ids(self):
182
return self._format.supports_setting_file_ids
184
def get_config_stack(self):
185
"""Retrieve the config stack for this tree.
187
:return: A ``breezy.config.Stack``
189
# For the moment, just provide the branch config stack.
190
return self.branch.get_config_stack()
193
def open(path=None, _unsupported=False):
194
"""Open an existing working tree at path.
198
path = osutils.getcwd()
199
control = controldir.ControlDir.open(path, _unsupported=_unsupported)
200
return control.open_workingtree(unsupported=_unsupported)
203
def open_containing(path=None):
204
"""Open an existing working tree which has its root about path.
206
This probes for a working tree at path and searches upwards from there.
208
Basically we keep looking up until we find the control directory or
209
run into /. If there isn't one, raises NotBranchError.
210
TODO: give this a new exception.
211
If there is one, it is returned, along with the unused portion of path.
213
:return: The WorkingTree that contains 'path', and the rest of path
216
path = osutils.getcwd()
217
control, relpath = controldir.ControlDir.open_containing(path)
218
return control.open_workingtree(), relpath
221
def open_containing_paths(file_list, default_directory=None,
222
canonicalize=True, apply_view=True):
223
"""Open the WorkingTree that contains a set of paths.
225
Fail if the paths given are not all in a single tree.
227
This is used for the many command-line interfaces that take a list of
228
any number of files and that require they all be in the same tree.
230
if default_directory is None:
231
default_directory = u'.'
232
# recommended replacement for builtins.internal_tree_files
233
if file_list is None or len(file_list) == 0:
234
tree = WorkingTree.open_containing(default_directory)[0]
235
# XXX: doesn't really belong here, and seems to have the strange
236
# side effect of making it return a bunch of files, not the whole
237
# tree -- mbp 20100716
238
if tree.supports_views() and apply_view:
239
view_files = tree.views.lookup_view()
241
file_list = view_files
242
view_str = views.view_display_str(view_files)
243
note(gettext("Ignoring files outside view. View is %s") % view_str)
244
return tree, file_list
245
if default_directory == u'.':
248
seed = default_directory
249
file_list = [osutils.pathjoin(default_directory, f)
251
tree = WorkingTree.open_containing(seed)[0]
252
return tree, tree.safe_relpath_files(file_list, canonicalize,
253
apply_view=apply_view)
255
def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
256
"""Convert file_list into a list of relpaths in tree.
258
:param self: A tree to operate on.
259
:param file_list: A list of user provided paths or None.
260
:param apply_view: if True and a view is set, apply it or check that
261
specified files are within it
262
:return: A list of relative paths.
263
:raises errors.PathNotChild: When a provided path is in a different self
266
if file_list is None:
268
if self.supports_views() and apply_view:
269
view_files = self.views.lookup_view()
273
# self.relpath exists as a "thunk" to osutils, but canonical_relpath
274
# doesn't - fix that up here before we enter the loop.
277
return osutils.canonical_relpath(self.basedir, p)
280
for filename in file_list:
281
relpath = fixer(osutils.dereference_path(filename))
282
if view_files and not osutils.is_inside_any(view_files, relpath):
283
raise views.FileOutsideView(filename, view_files)
284
new_list.append(relpath)
288
def open_downlevel(path=None):
289
"""Open an unsupported working tree.
291
Only intended for advanced situations like upgrading part of a controldir.
293
return WorkingTree.open(path, _unsupported=True)
296
def find_trees(location):
297
def list_current(transport):
298
return [d for d in transport.list_dir('')
299
if not controldir.is_control_filename(d)]
301
def evaluate(controldir):
303
tree = controldir.open_workingtree()
304
except errors.NoWorkingTree:
308
t = transport.get_transport(location)
309
iterator = controldir.ControlDir.find_controldirs(t, evaluate=evaluate,
310
list_current=list_current)
311
return [tr for tr in iterator if tr is not None]
314
return "<%s of %s>" % (self.__class__.__name__,
315
getattr(self, 'basedir', None))
317
def abspath(self, filename):
318
return osutils.pathjoin(self.basedir, filename)
320
def basis_tree(self):
321
"""Return RevisionTree for the current last revision.
323
If the left most parent is a ghost then the returned tree will be an
324
empty tree - one obtained by calling
325
repository.revision_tree(NULL_REVISION).
328
revision_id = self.get_parent_ids()[0]
330
# no parents, return an empty revision tree.
331
# in the future this should return the tree for
332
# 'empty:' - the implicit root empty tree.
333
return self.branch.repository.revision_tree(
334
_mod_revision.NULL_REVISION)
336
return self.revision_tree(revision_id)
337
except errors.NoSuchRevision:
339
# No cached copy available, retrieve from the repository.
340
# FIXME? RBC 20060403 should we cache the tree locally
343
return self.branch.repository.revision_tree(revision_id)
344
except (errors.RevisionNotPresent, errors.NoSuchRevision):
345
# the basis tree *may* be a ghost or a low level error may have
346
# occurred. If the revision is present, its a problem, if its not
348
if self.branch.repository.has_revision(revision_id):
350
# the basis tree is a ghost so return an empty tree.
351
return self.branch.repository.revision_tree(
352
_mod_revision.NULL_REVISION)
354
def relpath(self, path):
355
"""Return the local path portion from a given path.
357
The path may be absolute or relative. If its a relative path it is
358
interpreted relative to the python current working directory.
360
return osutils.relpath(self.basedir, path)
362
def has_filename(self, filename):
363
return osutils.lexists(self.abspath(filename))
365
def get_file(self, path, file_id=None, filtered=True):
366
return self.get_file_with_stat(path, file_id, filtered=filtered)[0]
368
def get_file_with_stat(self, path, file_id=None, filtered=True,
369
_fstat=osutils.fstat):
370
"""See Tree.get_file_with_stat."""
371
abspath = self.abspath(path)
373
file_obj = open(abspath, 'rb')
374
except EnvironmentError as e:
375
if e.errno == errno.ENOENT:
376
raise errors.NoSuchFile(path)
378
stat_value = _fstat(file_obj.fileno())
379
if filtered and self.supports_content_filtering():
380
filters = self._content_filter_stack(path)
381
file_obj = _mod_filters.filtered_input_file(file_obj, filters)
382
return (file_obj, stat_value)
384
def get_file_text(self, path, file_id=None, filtered=True):
385
with self.get_file(path, file_id, filtered=filtered) as my_file:
386
return my_file.read()
388
def get_file_lines(self, path, file_id=None, filtered=True):
389
"""See Tree.get_file_lines()"""
390
with self.get_file(path, file_id, filtered=filtered) as file:
391
return file.readlines()
393
def get_parent_ids(self):
394
"""See Tree.get_parent_ids.
396
This implementation reads the pending merges list and last_revision
397
value and uses that to decide what the parents list should be.
399
last_rev = _mod_revision.ensure_null(self._last_revision())
400
if _mod_revision.NULL_REVISION == last_rev:
405
merges_bytes = self._transport.get_bytes('pending-merges')
406
except errors.NoSuchFile:
409
for l in osutils.split_lines(merges_bytes):
410
revision_id = l.rstrip(b'\n')
411
parents.append(revision_id)
414
def get_root_id(self):
415
"""Return the id of this trees root"""
416
raise NotImplementedError(self.get_root_id)
418
def clone(self, to_controldir, revision_id=None):
419
"""Duplicate this working tree into to_bzr, including all state.
421
Specifically modified files are kept as modified, but
422
ignored and unknown files are discarded.
424
If you want to make a new line of development, see ControlDir.sprout()
427
If not None, the cloned tree will have its last revision set to
428
revision, and difference between the source trees last revision
429
and this one merged in.
431
with self.lock_read():
432
# assumes the target bzr dir format is compatible.
433
result = to_controldir.create_workingtree()
434
self.copy_content_into(result, revision_id)
437
def copy_content_into(self, tree, revision_id=None):
438
"""Copy the current content and user files of this tree into tree."""
439
with self.lock_read():
440
tree.set_root_id(self.get_root_id())
441
if revision_id is None:
442
merge.transform_tree(tree, self)
444
# TODO now merge from tree.last_revision to revision (to
445
# preserve user local changes)
447
other_tree = self.revision_tree(revision_id)
448
except errors.NoSuchRevision:
449
other_tree = self.branch.repository.revision_tree(
452
merge.transform_tree(tree, other_tree)
453
if revision_id == _mod_revision.NULL_REVISION:
456
new_parents = [revision_id]
457
tree.set_parent_ids(new_parents)
459
def get_file_size(self, path, file_id=None):
460
"""See Tree.get_file_size"""
461
# XXX: this returns the on-disk size; it should probably return the
464
return os.path.getsize(self.abspath(path))
466
if e.errno != errno.ENOENT:
471
def _gather_kinds(self, files, kinds):
472
"""See MutableTree._gather_kinds."""
473
with self.lock_tree_write():
474
for pos, f in enumerate(files):
475
if kinds[pos] is None:
476
fullpath = osutils.normpath(self.abspath(f))
478
kinds[pos] = osutils.file_kind(fullpath)
480
if e.errno == errno.ENOENT:
481
raise errors.NoSuchFile(fullpath)
483
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
484
"""Add revision_id as a parent.
486
This is equivalent to retrieving the current list of parent ids
487
and setting the list to its value plus revision_id.
489
:param revision_id: The revision id to add to the parent list. It may
490
be a ghost revision as long as its not the first parent to be
491
added, or the allow_leftmost_as_ghost parameter is set True.
492
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
494
with self.lock_write():
495
parents = self.get_parent_ids() + [revision_id]
496
self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
497
or allow_leftmost_as_ghost)
499
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
500
"""Add revision_id, tree tuple as a parent.
502
This is equivalent to retrieving the current list of parent trees
503
and setting the list to its value plus parent_tuple. See also
504
add_parent_tree_id - if you only have a parent id available it will be
505
simpler to use that api. If you have the parent already available, using
506
this api is preferred.
508
:param parent_tuple: The (revision id, tree) to add to the parent list.
509
If the revision_id is a ghost, pass None for the tree.
510
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
512
with self.lock_tree_write():
513
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
514
if len(parent_ids) > 1:
515
# the leftmost may have already been a ghost, preserve that if it
517
allow_leftmost_as_ghost = True
518
self.set_parent_ids(parent_ids,
519
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
521
def add_pending_merge(self, *revision_ids):
522
with self.lock_tree_write():
523
# TODO: Perhaps should check at this point that the
524
# history of the revision is actually present?
525
parents = self.get_parent_ids()
527
for rev_id in revision_ids:
528
if rev_id in parents:
530
parents.append(rev_id)
533
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
535
def path_content_summary(self, path, _lstat=os.lstat,
536
_mapper=osutils.file_kind_from_stat_mode):
537
"""See Tree.path_content_summary."""
538
abspath = self.abspath(path)
540
stat_result = _lstat(abspath)
542
if getattr(e, 'errno', None) == errno.ENOENT:
544
return ('missing', None, None, None)
545
# propagate other errors
547
kind = _mapper(stat_result.st_mode)
549
return self._file_content_summary(path, stat_result)
550
elif kind == 'directory':
551
# perhaps it looks like a plain directory, but it's really a
553
if self._directory_is_tree_reference(path):
554
kind = 'tree-reference'
555
return kind, None, None, None
556
elif kind == 'symlink':
557
target = osutils.readlink(abspath)
558
return ('symlink', None, None, target)
560
return (kind, None, None, None)
562
def _file_content_summary(self, path, stat_result):
563
size = stat_result.st_size
564
executable = self._is_executable_from_path_and_stat(path, stat_result)
565
# try for a stat cache lookup
566
return ('file', size, executable, self._sha_from_stat(
569
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
570
"""Common ghost checking functionality from set_parent_*.
572
This checks that the left hand-parent exists if there are any
575
if len(revision_ids) > 0:
576
leftmost_id = revision_ids[0]
577
if (not allow_leftmost_as_ghost and not
578
self.branch.repository.has_revision(leftmost_id)):
579
raise errors.GhostRevisionUnusableHere(leftmost_id)
581
def _set_merges_from_parent_ids(self, parent_ids):
582
merges = parent_ids[1:]
583
self._transport.put_bytes('pending-merges', b'\n'.join(merges),
584
mode=self.controldir._get_file_mode())
586
def _filter_parent_ids_by_ancestry(self, revision_ids):
587
"""Check that all merged revisions are proper 'heads'.
589
This will always return the first revision_id, and any merged revisions
592
if len(revision_ids) == 0:
594
graph = self.branch.repository.get_graph()
595
heads = graph.heads(revision_ids)
596
new_revision_ids = revision_ids[:1]
597
for revision_id in revision_ids[1:]:
598
if revision_id in heads and revision_id not in new_revision_ids:
599
new_revision_ids.append(revision_id)
600
if new_revision_ids != revision_ids:
601
mutter('requested to set revision_ids = %s,'
602
' but filtered to %s', revision_ids, new_revision_ids)
603
return new_revision_ids
605
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
606
"""Set the parent ids to revision_ids.
608
See also set_parent_trees. This api will try to retrieve the tree data
609
for each element of revision_ids from the trees repository. If you have
610
tree data already available, it is more efficient to use
611
set_parent_trees rather than set_parent_ids. set_parent_ids is however
612
an easier API to use.
614
:param revision_ids: The revision_ids to set as the parent ids of this
615
working tree. Any of these may be ghosts.
617
with self.lock_tree_write():
618
self._check_parents_for_ghosts(revision_ids,
619
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
620
for revision_id in revision_ids:
621
_mod_revision.check_not_reserved_id(revision_id)
623
revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
625
if len(revision_ids) > 0:
626
self.set_last_revision(revision_ids[0])
628
self.set_last_revision(_mod_revision.NULL_REVISION)
630
self._set_merges_from_parent_ids(revision_ids)
632
def set_pending_merges(self, rev_list):
633
with self.lock_tree_write():
634
parents = self.get_parent_ids()
635
leftmost = parents[:1]
636
new_parents = leftmost + rev_list
637
self.set_parent_ids(new_parents)
639
def set_merge_modified(self, modified_hashes):
640
"""Set the merge modified hashes."""
641
raise NotImplementedError(self.set_merge_modified)
643
def _sha_from_stat(self, path, stat_result):
644
"""Get a sha digest from the tree's stat cache.
646
The default implementation assumes no stat cache is present.
648
:param path: The path.
649
:param stat_result: The stat result being looked up.
653
def merge_from_branch(self, branch, to_revision=None, from_revision=None,
654
merge_type=None, force=False):
655
"""Merge from a branch into this working tree.
657
:param branch: The branch to merge from.
658
:param to_revision: If non-None, the merge will merge to to_revision,
659
but not beyond it. to_revision does not need to be in the history
660
of the branch when it is supplied. If None, to_revision defaults to
661
branch.last_revision().
663
from .merge import Merger, Merge3Merger
664
with self.lock_write():
665
merger = Merger(self.branch, this_tree=self)
666
# check that there are no local alterations
667
if not force and self.has_changes():
668
raise errors.UncommittedChanges(self)
669
if to_revision is None:
670
to_revision = _mod_revision.ensure_null(branch.last_revision())
671
merger.other_rev_id = to_revision
672
if _mod_revision.is_null(merger.other_rev_id):
673
raise errors.NoCommits(branch)
674
self.branch.fetch(branch, last_revision=merger.other_rev_id)
675
merger.other_basis = merger.other_rev_id
676
merger.other_tree = self.branch.repository.revision_tree(
678
merger.other_branch = branch
679
if from_revision is None:
682
merger.set_base_revision(from_revision, branch)
683
if merger.base_rev_id == merger.other_rev_id:
684
raise errors.PointlessMerge
685
merger.backup_files = False
686
if merge_type is None:
687
merger.merge_type = Merge3Merger
689
merger.merge_type = merge_type
690
merger.set_interesting_files(None)
691
merger.show_base = False
692
merger.reprocess = False
693
conflicts = merger.do_merge()
697
def merge_modified(self):
698
"""Return a dictionary of files modified by a merge.
700
The list is initialized by WorkingTree.set_merge_modified, which is
701
typically called after we make some automatic updates to the tree
704
This returns a map of file_id->sha1, containing only files which are
705
still in the working tree and have that text hash.
707
raise NotImplementedError(self.merge_modified)
709
def mkdir(self, path, file_id=None):
710
"""See MutableTree.mkdir()."""
712
if self.supports_setting_file_ids():
713
file_id = generate_ids.gen_file_id(os.path.basename(path))
715
if not self.supports_setting_file_ids():
716
raise SettingFileIdUnsupported()
717
with self.lock_write():
718
os.mkdir(self.abspath(path))
719
self.add(path, file_id, 'directory')
722
def get_symlink_target(self, path, file_id=None):
723
abspath = self.abspath(path)
724
target = osutils.readlink(abspath)
727
def subsume(self, other_tree):
728
raise NotImplementedError(self.subsume)
730
def _setup_directory_is_tree_reference(self):
731
if self._branch.repository._format.supports_tree_reference:
732
self._directory_is_tree_reference = \
733
self._directory_may_be_tree_reference
735
self._directory_is_tree_reference = \
736
self._directory_is_never_tree_reference
738
def _directory_is_never_tree_reference(self, relpath):
741
def _directory_may_be_tree_reference(self, relpath):
742
# as a special case, if a directory contains control files then
743
# it's a tree reference, except that the root of the tree is not
744
return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
745
# TODO: We could ask all the control formats whether they
746
# recognize this directory, but at the moment there's no cheap api
747
# to do that. Since we probably can only nest bzr checkouts and
748
# they always use this name it's ok for now. -- mbp 20060306
750
# FIXME: There is an unhandled case here of a subdirectory
751
# containing .bzr but not a branch; that will probably blow up
752
# when you try to commit it. It might happen if there is a
753
# checkout in a subdirectory. This can be avoided by not adding
756
def extract(self, path, file_id=None, format=None):
757
"""Extract a subtree from this tree.
759
A new branch will be created, relative to the path for this tree.
761
raise NotImplementedError(self.extract)
764
"""Write the in memory meta data to disk."""
765
raise NotImplementedError(self.flush)
767
def kind(self, relpath, file_id=None):
768
return osutils.file_kind(self.abspath(relpath))
770
def list_files(self, include_root=False, from_dir=None, recursive=True):
771
"""List all files as (path, class, kind, id, entry).
773
Lists, but does not descend into unversioned directories.
774
This does not include files that have been deleted in this
775
tree. Skips the control directory.
777
:param include_root: if True, return an entry for the root
778
:param from_dir: start from this directory or None for the root
779
:param recursive: whether to recurse into subdirectories or not
781
raise NotImplementedError(self.list_files)
783
def move(self, from_paths, to_dir=None, after=False):
786
to_dir must be known to the working tree.
788
If to_dir exists and is a directory, the files are moved into
789
it, keeping their old names.
791
Note that to_dir is only the last component of the new name;
792
this doesn't change the directory.
794
For each entry in from_paths the move mode will be determined
797
The first mode moves the file in the filesystem and updates the
798
working tree metadata. The second mode only updates the working tree
799
metadata without touching the file on the filesystem.
801
move uses the second mode if 'after == True' and the target is not
802
versioned but present in the working tree.
804
move uses the second mode if 'after == False' and the source is
805
versioned but no longer in the working tree, and the target is not
806
versioned but present in the working tree.
808
move uses the first mode if 'after == False' and the source is
809
versioned and present in the working tree, and the target is not
810
versioned and not present in the working tree.
812
Everything else results in an error.
814
This returns a list of (from_path, to_path) pairs for each
817
raise NotImplementedError(self.move)
819
def copy_one(self, from_rel, to_rel):
820
"""Copy a file in the tree to a new location.
822
This default implementation just copies the file, then
825
:param from_rel: From location (relative to tree root)
826
:param to_rel: Target location (relative to tree root)
828
shutil.copyfile(self.abspath(from_rel), self.abspath(to_rel))
832
"""Return all unknown files.
834
These are files in the working directory that are not versioned or
835
control files or ignored.
837
with self.lock_read():
838
# force the extras method to be fully executed before returning, to
839
# prevent race conditions with the lock
841
[subp for subp in self.extras() if not self.is_ignored(subp)])
843
def unversion(self, paths):
844
"""Remove the path in pahs from the current versioned set.
846
When a path is unversioned, all of its children are automatically
849
:param paths: The paths to stop versioning.
850
:raises NoSuchFile: if any path is not currently versioned.
852
raise NotImplementedError(self.unversion)
854
def pull(self, source, overwrite=False, stop_revision=None,
855
change_reporter=None, possible_transports=None, local=False,
857
with self.lock_write(), source.lock_read():
858
old_revision_info = self.branch.last_revision_info()
859
basis_tree = self.basis_tree()
860
count = self.branch.pull(source, overwrite, stop_revision,
861
possible_transports=possible_transports,
863
new_revision_info = self.branch.last_revision_info()
864
if new_revision_info != old_revision_info:
865
repository = self.branch.repository
866
if repository._format.fast_deltas:
867
parent_ids = self.get_parent_ids()
869
basis_id = parent_ids[0]
870
basis_tree = repository.revision_tree(basis_id)
871
with basis_tree.lock_read():
872
new_basis_tree = self.branch.basis_tree()
878
change_reporter=change_reporter,
880
basis_root_id = basis_tree.get_root_id()
881
new_root_id = new_basis_tree.get_root_id()
882
if new_root_id is not None and basis_root_id != new_root_id:
883
self.set_root_id(new_root_id)
884
# TODO - dedup parents list with things merged by pull ?
885
# reuse the revisiontree we merged against to set the new
888
if self.branch.last_revision() != _mod_revision.NULL_REVISION:
890
(self.branch.last_revision(), new_basis_tree))
891
# we have to pull the merge trees out again, because
892
# merge_inner has set the ids. - this corner is not yet
893
# layered well enough to prevent double handling.
894
# XXX TODO: Fix the double handling: telling the tree about
895
# the already known parent data is wasteful.
896
merges = self.get_parent_ids()[1:]
897
parent_trees.extend([
898
(parent, repository.revision_tree(parent)) for
900
self.set_parent_trees(parent_trees)
903
def put_file_bytes_non_atomic(self, path, bytes, file_id=None):
904
"""See MutableTree.put_file_bytes_non_atomic."""
905
with self.lock_write(), open(self.abspath(path), 'wb') as stream:
909
"""Yield all unversioned files in this WorkingTree.
911
If there are any unversioned directories then only the directory is
912
returned, not all its children. But if there are unversioned files
913
under a versioned subdirectory, they are returned.
915
Currently returned depth-first, sorted by name within directories.
916
This is the same order used by 'osutils.walkdirs'.
918
raise NotImplementedError(self.extras)
920
def ignored_files(self):
921
"""Yield list of PATH, IGNORE_PATTERN"""
922
for subp in self.extras():
923
pat = self.is_ignored(subp)
927
def is_ignored(self, filename):
928
r"""Check whether the filename matches an ignore pattern.
930
raise NotImplementedError(self.is_ignored)
932
def stored_kind(self, path, file_id=None):
933
"""See Tree.stored_kind"""
934
raise NotImplementedError(self.stored_kind)
936
def _comparison_data(self, entry, path):
937
abspath = self.abspath(path)
939
stat_value = os.lstat(abspath)
941
if getattr(e, 'errno', None) == errno.ENOENT:
948
mode = stat_value.st_mode
949
kind = osutils.file_kind_from_stat_mode(mode)
950
if not self._supports_executable():
951
executable = entry is not None and entry.executable
953
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
954
return kind, executable, stat_value
956
def last_revision(self):
957
"""Return the last revision of the branch for this tree.
959
This format tree does not support a separate marker for last-revision
960
compared to the branch.
962
See MutableTree.last_revision
964
return self._last_revision()
966
def _last_revision(self):
967
"""helper for get_parent_ids."""
968
with self.lock_read():
969
return _mod_revision.ensure_null(self.branch.last_revision())
972
"""Check if this tree is locked."""
973
raise NotImplementedError(self.is_locked)
976
"""Lock the tree for reading.
978
This also locks the branch, and can be unlocked via self.unlock().
980
:return: A breezy.lock.LogicalLockResult.
982
raise NotImplementedError(self.lock_read)
984
def lock_tree_write(self):
985
"""See MutableTree.lock_tree_write, and WorkingTree.unlock.
987
:return: A breezy.lock.LogicalLockResult.
989
raise NotImplementedError(self.lock_tree_write)
991
def lock_write(self):
992
"""See MutableTree.lock_write, and WorkingTree.unlock.
994
:return: A breezy.lock.LogicalLockResult.
996
raise NotImplementedError(self.lock_write)
998
def get_physical_lock_status(self):
999
raise NotImplementedError(self.get_physical_lock_status)
1001
def set_last_revision(self, new_revision):
1002
"""Change the last revision in the working tree."""
1003
raise NotImplementedError(self.set_last_revision)
1005
def _change_last_revision(self, new_revision):
1006
"""Template method part of set_last_revision to perform the change.
1008
This is used to allow WorkingTree3 instances to not affect branch
1009
when their last revision is set.
1011
if _mod_revision.is_null(new_revision):
1012
self.branch.set_last_revision_info(0, new_revision)
1014
_mod_revision.check_not_reserved_id(new_revision)
1016
self.branch.generate_revision_history(new_revision)
1017
except errors.NoSuchRevision:
1018
# not present in the repo - dont try to set it deeper than the tip
1019
self.branch._set_revision_history([new_revision])
1022
def remove(self, files, verbose=False, to_file=None, keep_files=True,
1024
"""Remove nominated files from the working tree metadata.
1026
:files: File paths relative to the basedir.
1027
:keep_files: If true, the files will also be kept.
1028
:force: Delete files and directories, even if they are changed and
1029
even if the directories are not empty.
1031
raise NotImplementedError(self.remove)
1033
def revert(self, filenames=None, old_tree=None, backups=True,
1034
pb=None, report_changes=False):
1035
from .conflicts import resolve
1036
with self.lock_tree_write():
1037
if old_tree is None:
1038
basis_tree = self.basis_tree()
1039
basis_tree.lock_read()
1040
old_tree = basis_tree
1044
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1046
if filenames is None and len(self.get_parent_ids()) > 1:
1048
last_revision = self.last_revision()
1049
if last_revision != _mod_revision.NULL_REVISION:
1050
if basis_tree is None:
1051
basis_tree = self.basis_tree()
1052
basis_tree.lock_read()
1053
parent_trees.append((last_revision, basis_tree))
1054
self.set_parent_trees(parent_trees)
1057
resolve(self, filenames, ignore_misses=True, recursive=True)
1059
if basis_tree is not None:
1063
def store_uncommitted(self):
1064
"""Store uncommitted changes from the tree in the branch."""
1065
raise NotImplementedError(self.store_uncommitted)
1067
def restore_uncommitted(self):
1068
"""Restore uncommitted changes from the branch into the tree."""
1069
raise NotImplementedError(self.restore_uncommitted)
1071
def revision_tree(self, revision_id):
1072
"""See Tree.revision_tree.
1074
For trees that can be obtained from the working tree, this
1075
will do so. For other trees, it will fall back to the repository.
1077
raise NotImplementedError(self.revision_tree)
1079
def set_root_id(self, file_id):
1080
"""Set the root id for this tree."""
1081
if not self.supports_setting_file_ids():
1082
raise SettingFileIdUnsupported()
1083
with self.lock_tree_write():
1087
'WorkingTree.set_root_id with fileid=None')
1088
file_id = osutils.safe_file_id(file_id)
1089
self._set_root_id(file_id)
1091
def _set_root_id(self, file_id):
1092
"""Set the root id for this tree, in a format specific manner.
1094
:param file_id: The file id to assign to the root. It must not be
1095
present in the current inventory or an error will occur. It must
1096
not be None, but rather a valid file id.
1098
raise NotImplementedError(self._set_root_id)
1101
"""See Branch.unlock.
1103
WorkingTree locking just uses the Branch locking facilities.
1104
This is current because all working trees have an embedded branch
1105
within them. IF in the future, we were to make branch data shareable
1106
between multiple working trees, i.e. via shared storage, then we
1107
would probably want to lock both the local tree, and the branch.
1109
raise NotImplementedError(self.unlock)
1113
def update(self, change_reporter=None, possible_transports=None,
1114
revision=None, old_tip=_marker, show_base=False):
1115
"""Update a working tree along its branch.
1117
This will update the branch if its bound too, which means we have
1118
multiple trees involved:
1120
- The new basis tree of the master.
1121
- The old basis tree of the branch.
1122
- The old basis tree of the working tree.
1123
- The current working tree state.
1125
Pathologically, all three may be different, and non-ancestors of each
1126
other. Conceptually we want to:
1128
- Preserve the wt.basis->wt.state changes
1129
- Transform the wt.basis to the new master basis.
1130
- Apply a merge of the old branch basis to get any 'local' changes from
1132
- Restore the wt.basis->wt.state changes.
1134
There isn't a single operation at the moment to do that, so we:
1136
- Merge current state -> basis tree of the master w.r.t. the old tree
1138
- Do a 'normal' merge of the old branch basis if it is relevant.
1140
:param revision: The target revision to update to. Must be in the
1142
:param old_tip: If branch.update() has already been run, the value it
1143
returned (old tip of the branch or None). _marker is used
1146
if self.branch.get_bound_location() is not None:
1148
update_branch = (old_tip is self._marker)
1150
self.lock_tree_write()
1151
update_branch = False
1154
old_tip = self.branch.update(possible_transports)
1156
if old_tip is self._marker:
1158
return self._update_tree(old_tip, change_reporter, revision, show_base)
1162
def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
1164
"""Update a tree to the master branch.
1166
:param old_tip: if supplied, the previous tip revision the branch,
1167
before it was changed to the master branch's tip.
1169
# here if old_tip is not None, it is the old tip of the branch before
1170
# it was updated from the master branch. This should become a pending
1171
# merge in the working tree to preserve the user existing work. we
1172
# cant set that until we update the working trees last revision to be
1173
# one from the new branch, because it will just get absorbed by the
1174
# parent de-duplication logic.
1176
# We MUST save it even if an error occurs, because otherwise the users
1177
# local work is unreferenced and will appear to have been lost.
1179
with self.lock_tree_write():
1182
last_rev = self.get_parent_ids()[0]
1184
last_rev = _mod_revision.NULL_REVISION
1185
if revision is None:
1186
revision = self.branch.last_revision()
1188
old_tip = old_tip or _mod_revision.NULL_REVISION
1190
if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
1191
# the branch we are bound to was updated
1192
# merge those changes in first
1193
base_tree = self.basis_tree()
1194
other_tree = self.branch.repository.revision_tree(old_tip)
1195
nb_conflicts = merge.merge_inner(self.branch, other_tree,
1196
base_tree, this_tree=self,
1197
change_reporter=change_reporter,
1198
show_base=show_base)
1200
self.add_parent_tree((old_tip, other_tree))
1201
note(gettext('Rerun update after fixing the conflicts.'))
1204
if last_rev != _mod_revision.ensure_null(revision):
1205
# the working tree is up to date with the branch
1206
# we can merge the specified revision from master
1207
to_tree = self.branch.repository.revision_tree(revision)
1208
to_root_id = to_tree.get_root_id()
1210
basis = self.basis_tree()
1211
with basis.lock_read():
1212
if (basis.get_root_id() is None or basis.get_root_id() != to_root_id):
1213
self.set_root_id(to_root_id)
1216
# determine the branch point
1217
graph = self.branch.repository.get_graph()
1218
base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
1220
base_tree = self.branch.repository.revision_tree(base_rev_id)
1222
nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
1224
change_reporter=change_reporter,
1225
show_base=show_base)
1226
self.set_last_revision(revision)
1227
# TODO - dedup parents list with things merged by pull ?
1228
# reuse the tree we've updated to to set the basis:
1229
parent_trees = [(revision, to_tree)]
1230
merges = self.get_parent_ids()[1:]
1231
# Ideally we ask the tree for the trees here, that way the working
1232
# tree can decide whether to give us the entire tree or give us a
1233
# lazy initialised tree. dirstate for instance will have the trees
1234
# in ram already, whereas a last-revision + basis-inventory tree
1235
# will not, but also does not need them when setting parents.
1236
for parent in merges:
1237
parent_trees.append(
1238
(parent, self.branch.repository.revision_tree(parent)))
1239
if not _mod_revision.is_null(old_tip):
1240
parent_trees.append(
1241
(old_tip, self.branch.repository.revision_tree(old_tip)))
1242
self.set_parent_trees(parent_trees)
1243
last_rev = parent_trees[0][0]
1246
def set_conflicts(self, arg):
1247
raise errors.UnsupportedOperation(self.set_conflicts, self)
1249
def add_conflicts(self, arg):
1250
raise errors.UnsupportedOperation(self.add_conflicts, self)
1252
def conflicts(self):
1253
raise NotImplementedError(self.conflicts)
1255
def walkdirs(self, prefix=""):
1256
"""Walk the directories of this tree.
1258
returns a generator which yields items in the form:
1259
((curren_directory_path, fileid),
1260
[(file1_path, file1_name, file1_kind, (lstat), file1_id,
1263
This API returns a generator, which is only valid during the current
1264
tree transaction - within a single lock_read or lock_write duration.
1266
If the tree is not locked, it may cause an error to be raised,
1267
depending on the tree implementation.
1269
raise NotImplementedError(self.walkdirs)
1271
def auto_resolve(self):
1272
"""Automatically resolve text conflicts according to contents.
1274
Only text conflicts are auto_resolvable. Files with no conflict markers
1275
are considered 'resolved', because bzr always puts conflict markers
1276
into files that have text conflicts. The corresponding .THIS .BASE and
1277
.OTHER files are deleted, as per 'resolve'.
1279
:return: a tuple of ConflictLists: (un_resolved, resolved).
1281
with self.lock_tree_write():
1282
un_resolved = _mod_conflicts.ConflictList()
1283
resolved = _mod_conflicts.ConflictList()
1284
conflict_re = re.compile(b'^(<{7}|={7}|>{7})')
1285
for conflict in self.conflicts():
1286
path = self.id2path(conflict.file_id)
1287
if (conflict.typestring != 'text conflict' or
1288
self.kind(path) != 'file'):
1289
un_resolved.append(conflict)
1291
with open(self.abspath(path), 'rb') as my_file:
1292
for line in my_file:
1293
if conflict_re.search(line):
1294
un_resolved.append(conflict)
1297
resolved.append(conflict)
1298
resolved.remove_files(self)
1299
self.set_conflicts(un_resolved)
1300
return un_resolved, resolved
1302
def _validate(self):
1303
"""Validate internal structures.
1305
This is meant mostly for the test suite. To give it a chance to detect
1306
corruption after actions have occurred. The default implementation is a
1309
:return: None. An exception should be raised if there is an error.
1313
def check_state(self):
1314
"""Check that the working state is/isn't valid."""
1315
raise NotImplementedError(self.check_state)
1317
def reset_state(self, revision_ids=None):
1318
"""Reset the state of the working tree.
1320
This does a hard-reset to a last-known-good state. This is a way to
1321
fix if something got corrupted (like the .bzr/checkout/dirstate file)
1323
raise NotImplementedError(self.reset_state)
1325
def _get_rules_searcher(self, default_searcher):
1326
"""See Tree._get_rules_searcher."""
1327
if self._rules_searcher is None:
1328
self._rules_searcher = super(WorkingTree,
1329
self)._get_rules_searcher(default_searcher)
1330
return self._rules_searcher
1332
def get_shelf_manager(self):
1333
"""Return the ShelfManager for this WorkingTree."""
1334
raise NotImplementedError(self.get_shelf_manager)
1336
def get_canonical_paths(self, paths):
1337
"""Like get_canonical_path() but works on multiple items.
1339
:param paths: A sequence of paths relative to the root of the tree.
1340
:return: A list of paths, with each item the corresponding input path
1341
adjusted to account for existing elements that match case
1344
with self.lock_read():
1348
def get_canonical_path(self, path):
1349
"""Returns the first item in the tree that matches a path.
1351
This is meant to allow case-insensitive path lookups on e.g.
1354
If a path matches exactly, it is returned. If no path matches exactly
1355
but more than one path matches according to the underlying file system,
1356
it is implementation defined which is returned.
1358
If no path matches according to the file system, the input path is
1359
returned, but with as many path entries that do exist changed to their
1362
If you need to resolve many names from the same tree, you should
1363
use get_canonical_paths() to avoid O(N) behaviour.
1365
:param path: A paths relative to the root of the tree.
1366
:return: The input path adjusted to account for existing elements
1367
that match case insensitively.
1369
with self.lock_read():
1370
return next(self.get_canonical_paths([path]))
1373
class WorkingTreeFormatRegistry(controldir.ControlComponentFormatRegistry):
1374
"""Registry for working tree formats."""
1376
def __init__(self, other_registry=None):
1377
super(WorkingTreeFormatRegistry, self).__init__(other_registry)
1378
self._default_format = None
1379
self._default_format_key = None
1381
def get_default(self):
1382
"""Return the current default format."""
1383
if (self._default_format_key is not None and
1384
self._default_format is None):
1385
self._default_format = self.get(self._default_format_key)
1386
return self._default_format
1388
def set_default(self, format):
1389
"""Set the default format."""
1390
self._default_format = format
1391
self._default_format_key = None
1393
def set_default_key(self, format_string):
1394
"""Set the default format by its format string."""
1395
self._default_format_key = format_string
1396
self._default_format = None
1399
format_registry = WorkingTreeFormatRegistry()
1402
class WorkingTreeFormat(controldir.ControlComponentFormat):
1403
"""An encapsulation of the initialization and open routines for a format.
1405
Formats provide three things:
1406
* An initialization routine,
1410
Formats are placed in an dict by their format string for reference
1411
during workingtree opening. Its not required that these be instances, they
1412
can be classes themselves with class methods - it simply depends on
1413
whether state is needed for a given format or not.
1415
Once a format is deprecated, just deprecate the initialize and open
1416
methods on the format class. Do not deprecate the object, as the
1417
object will be created every time regardless.
1420
requires_rich_root = False
1422
upgrade_recommended = False
1424
requires_normalized_unicode_filenames = False
1426
case_sensitive_filename = "FoRMaT"
1428
missing_parent_conflicts = False
1429
"""If this format supports missing parent conflicts."""
1431
supports_versioned_directories = None
1433
supports_merge_modified = True
1434
"""If this format supports storing merge modified hashes."""
1436
supports_setting_file_ids = True
1437
"""If this format allows setting the file id."""
1439
supports_store_uncommitted = True
1440
"""If this format supports shelve-like functionality."""
1442
supports_leftmost_parent_id_as_ghost = True
1444
supports_righthand_parent_id_as_ghost = True
1446
ignore_filename = None
1447
"""Name of file with ignore patterns, if any. """
1449
def initialize(self, controldir, revision_id=None, from_branch=None,
1450
accelerator_tree=None, hardlink=False):
1451
"""Initialize a new working tree in controldir.
1453
:param controldir: ControlDir to initialize the working tree in.
1454
:param revision_id: allows creating a working tree at a different
1455
revision than the branch is at.
1456
:param from_branch: Branch to checkout
1457
:param accelerator_tree: A tree which can be used for retrieving file
1458
contents more quickly than the revision tree, i.e. a workingtree.
1459
The revision tree will be used for cases where accelerator_tree's
1460
content is different.
1461
:param hardlink: If true, hard-link files from accelerator_tree,
1464
raise NotImplementedError(self.initialize)
1466
def __eq__(self, other):
1467
return self.__class__ is other.__class__
1469
def __ne__(self, other):
1470
return not (self == other)
1472
def get_format_description(self):
1473
"""Return the short description for this format."""
1474
raise NotImplementedError(self.get_format_description)
1476
def is_supported(self):
1477
"""Is this format supported?
1479
Supported formats can be initialized and opened.
1480
Unsupported formats may not support initialization or committing or
1481
some other features depending on the reason for not being supported.
1485
def supports_content_filtering(self):
1486
"""True if this format supports content filtering."""
1489
def supports_views(self):
1490
"""True if this format supports stored views."""
1493
def get_controldir_for_branch(self):
1494
"""Get the control directory format for creating branches.
1496
This is to support testing of working tree formats that can not exist
1497
in the same control directory as a branch.
1499
return self._matchingcontroldir
1502
format_registry.register_lazy(b"Bazaar Working Tree Format 4 (bzr 0.15)\n",
1503
"breezy.bzr.workingtree_4", "WorkingTreeFormat4")
1504
format_registry.register_lazy(b"Bazaar Working Tree Format 5 (bzr 1.11)\n",
1505
"breezy.bzr.workingtree_4", "WorkingTreeFormat5")
1506
format_registry.register_lazy(b"Bazaar Working Tree Format 6 (bzr 1.14)\n",
1507
"breezy.bzr.workingtree_4", "WorkingTreeFormat6")
1508
format_registry.register_lazy(b"Bazaar-NG Working Tree format 3",
1509
"breezy.bzr.workingtree_3", "WorkingTreeFormat3")
1510
format_registry.set_default_key(b"Bazaar Working Tree Format 6 (bzr 1.14)\n")