1
# Copyright (C) 2006-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
"""MutableTree object.
19
See MutableTree for more details.
22
from __future__ import absolute_import
38
class MutableTree(tree.Tree):
39
"""A MutableTree is a specialisation of Tree which is able to be mutated.
41
Generally speaking these mutations are only possible within a lock_write
42
context, and will revert if the lock is broken abnormally - but this cannot
43
be guaranteed - depending on the exact implementation of the mutable state.
45
The most common form of Mutable Tree is WorkingTree, see breezy.workingtree.
46
For tests we also have MemoryTree which is a MutableTree whose contents are
49
For now, we are not treating MutableTree as an interface to provide
50
conformance tests for - rather we are testing MemoryTree specifically, and
51
interface testing implementations of WorkingTree.
53
A mutable tree always has an associated Branch and ControlDir object - the
54
branch and bzrdir attributes.
56
def __init__(self, *args, **kw):
57
super(MutableTree, self).__init__(*args, **kw)
58
# Is this tree on a case-insensitive or case-preserving file-system?
59
# Sub-classes may initialize to False if they detect they are being
60
# used on media which doesn't differentiate the case of names.
61
self.case_sensitive = True
63
def is_control_filename(self, filename):
64
"""True if filename is the name of a control file in this tree.
66
:param filename: A filename within the tree. This is a relative path
67
from the root of this tree.
69
This is true IF and ONLY IF the filename is part of the meta data
70
that bzr controls in this tree. I.E. a random .bzr directory placed
71
on disk will not be a control file for this tree.
73
raise NotImplementedError(self.is_control_filename)
75
def add(self, files, ids=None, kinds=None):
76
"""Add paths to the set of versioned paths.
78
Note that the command line normally calls smart_add instead,
79
which can automatically recurse.
81
This adds the files to the inventory, so that they will be
82
recorded by the next commit.
84
:param files: List of paths to add, relative to the base of the tree.
85
:param ids: If set, use these instead of automatically generated ids.
86
Must be the same length as the list of files, but may
87
contain None for ids that are to be autogenerated.
88
:param kinds: Optional parameter to specify the kinds to be used for
91
TODO: Perhaps callback with the ids and paths as they're added.
93
if isinstance(files, (str, text_type)):
94
# XXX: Passing a single string is inconsistent and should be
96
if not (ids is None or isinstance(ids, (str, text_type))):
97
raise AssertionError()
98
if not (kinds is None or isinstance(kinds, (str, text_type))):
99
raise AssertionError()
103
if kinds is not None:
106
files = [path.strip('/') for path in files]
109
ids = [None] * len(files)
111
if not (len(ids) == len(files)):
112
raise AssertionError()
114
kinds = [None] * len(files)
115
elif not len(kinds) == len(files):
116
raise AssertionError()
117
with self.lock_tree_write():
119
# generic constraint checks:
120
if self.is_control_filename(f):
121
raise errors.ForbiddenControlFileError(filename=f)
122
fp = osutils.splitpath(f)
123
# fill out file kinds for all files [not needed when we stop
124
# caring about the instantaneous file kind within a uncommmitted tree
126
self._gather_kinds(files, kinds)
127
self._add(files, ids, kinds)
129
def add_reference(self, sub_tree):
130
"""Add a TreeReference to the tree, pointing at sub_tree"""
131
raise errors.UnsupportedOperation(self.add_reference, self)
133
def _add_reference(self, sub_tree):
134
"""Standard add_reference implementation, for use by subclasses"""
136
sub_tree_path = self.relpath(sub_tree.basedir)
137
except errors.PathNotChild:
138
raise errors.BadReferenceTarget(self, sub_tree,
139
'Target not inside tree.')
140
sub_tree_id = sub_tree.get_root_id()
141
if sub_tree_id == self.get_root_id():
142
raise errors.BadReferenceTarget(self, sub_tree,
143
'Trees have the same root id.')
144
if self.has_id(sub_tree_id):
145
raise errors.BadReferenceTarget(self, sub_tree,
146
'Root id already present in tree')
147
self._add([sub_tree_path], [sub_tree_id], ['tree-reference'])
149
def _add(self, files, ids, kinds):
150
"""Helper function for add - updates the inventory.
152
:param files: sequence of pathnames, relative to the tree root
153
:param ids: sequence of suggested ids for the files (may be None)
154
:param kinds: sequence of inventory kinds of the files (i.e. may
155
contain "tree-reference")
157
raise NotImplementedError(self._add)
159
def commit(self, message=None, revprops=None, *args, **kwargs):
160
# avoid circular imports
161
from breezy import commit
162
possible_master_transports=[]
163
with self.lock_write():
164
revprops = commit.Commit.update_revprops(
167
kwargs.pop('authors', None),
168
kwargs.get('local', False),
169
possible_master_transports)
170
# args for wt.commit start at message from the Commit.commit method,
171
args = (message, ) + args
172
for hook in MutableTree.hooks['start_commit']:
174
committed_id = commit.Commit().commit(working_tree=self,
176
possible_master_transports=possible_master_transports,
178
post_hook_params = PostCommitHookParams(self)
179
for hook in MutableTree.hooks['post_commit']:
180
hook(post_hook_params)
183
def _gather_kinds(self, files, kinds):
184
"""Helper function for add - sets the entries of kinds."""
185
raise NotImplementedError(self._gather_kinds)
187
def has_changes(self, _from_tree=None):
188
"""Quickly check that the tree contains at least one commitable change.
190
:param _from_tree: tree to compare against to find changes (default to
191
the basis tree and is intended to be used by tests).
193
:return: True if a change is found. False otherwise
195
with self.lock_read():
196
# Check pending merges
197
if len(self.get_parent_ids()) > 1:
199
if _from_tree is None:
200
_from_tree = self.basis_tree()
201
changes = self.iter_changes(_from_tree)
203
change = next(changes)
204
# Exclude root (talk about black magic... --vila 20090629)
205
if change[4] == (None, None):
206
change = next(changes)
208
except StopIteration:
212
def check_changed_or_out_of_date(self, strict, opt_name,
213
more_error, more_warning):
214
"""Check the tree for uncommitted changes and branch synchronization.
216
If strict is None and not set in the config files, a warning is issued.
217
If strict is True, an error is raised.
218
If strict is False, no checks are done and no warning is issued.
220
:param strict: True, False or None, searched in branch config if None.
222
:param opt_name: strict option name to search in config file.
224
:param more_error: Details about how to avoid the check.
226
:param more_warning: Details about what is happening.
228
with self.lock_read():
230
strict = self.branch.get_config_stack().get(opt_name)
231
if strict is not False:
233
if (self.has_changes()):
234
err_class = errors.UncommittedChanges
235
elif self.last_revision() != self.branch.last_revision():
236
# The tree has lost sync with its branch, there is little
237
# chance that the user is aware of it but he can still
238
# force the action with --no-strict
239
err_class = errors.OutOfDateTree
240
if err_class is not None:
242
err = err_class(self, more=more_warning)
243
# We don't want to interrupt the user if he expressed
244
# no preference about strict.
245
trace.warning('%s', err._format())
247
err = err_class(self, more=more_error)
250
def last_revision(self):
251
"""Return the revision id of the last commit performed in this tree.
253
In early tree formats the result of last_revision is the same as the
254
branch last_revision, but that is no longer the case for modern tree
257
last_revision returns the left most parent id, or None if there are no
260
last_revision was deprecated as of 0.11. Please use get_parent_ids
263
raise NotImplementedError(self.last_revision)
265
def lock_tree_write(self):
266
"""Lock the working tree for write, and the branch for read.
268
This is useful for operations which only need to mutate the working
269
tree. Taking out branch write locks is a relatively expensive process
270
and may fail if the branch is on read only media. So branch write locks
271
should only be taken out when we are modifying branch data - such as in
272
operations like commit, pull, uncommit and update.
274
raise NotImplementedError(self.lock_tree_write)
276
def lock_write(self):
277
"""Lock the tree and its branch. This allows mutating calls to be made.
279
Some mutating methods will take out implicit write locks, but in
280
general you should always obtain a write lock before calling mutating
283
raise NotImplementedError(self.lock_write)
285
def mkdir(self, path, file_id=None):
286
"""Create a directory in the tree. if file_id is None, one is assigned.
288
:param path: A unicode file path.
289
:param file_id: An optional file-id.
290
:return: the file id of the new directory.
292
raise NotImplementedError(self.mkdir)
294
def _observed_sha1(self, file_id, path, sha_and_stat):
295
"""Tell the tree we have observed a paths sha1.
297
The intent of this function is to allow trees that have a hashcache to
298
update the hashcache during commit. If the observed file is too new
299
(based on the stat_value) to be safely hash-cached the tree will ignore
302
The default implementation does nothing.
304
:param file_id: The file id
305
:param path: The file path
306
:param sha_and_stat: The sha 1 and stat result observed.
310
def put_file_bytes_non_atomic(self, file_id, bytes):
311
"""Update the content of a file in the tree.
313
Note that the file is written in-place rather than being
314
written to a temporary location and renamed. As a consequence,
315
readers can potentially see the file half-written.
317
:param file_id: file-id of the file
318
:param bytes: the new file contents
320
raise NotImplementedError(self.put_file_bytes_non_atomic)
322
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
323
"""Set the parents ids of the working tree.
325
:param revision_ids: A list of revision_ids.
327
raise NotImplementedError(self.set_parent_ids)
329
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
330
"""Set the parents of the working tree.
332
:param parents_list: A list of (revision_id, tree) tuples.
333
If tree is None, then that element is treated as an unreachable
334
parent tree - i.e. a ghost.
336
raise NotImplementedError(self.set_parent_trees)
338
def smart_add(self, file_list, recurse=True, action=None, save=True):
339
"""Version file_list, optionally recursing into directories.
341
This is designed more towards DWIM for humans than API clarity.
342
For the specific behaviour see the help for cmd_add().
344
:param file_list: List of zero or more paths. *NB: these are
345
interpreted relative to the process cwd, not relative to the
346
tree.* (Add and most other tree methods use tree-relative
348
:param action: A reporter to be called with the inventory, parent_ie,
349
path and kind of the path being added. It may return a file_id if
350
a specific one should be used.
351
:param save: Save the inventory after completing the adds. If False
352
this provides dry-run functionality by doing the add and not saving
354
:return: A tuple - files_added, ignored_files. files_added is the count
355
of added files, and ignored_files is a dict mapping files that were
356
ignored to the rule that caused them to be ignored.
358
raise NotImplementedError(self.smart_add)
361
class MutableTreeHooks(hooks.Hooks):
362
"""A dictionary mapping a hook name to a list of callables for mutabletree
367
"""Create the default hooks.
370
hooks.Hooks.__init__(self, "breezy.mutabletree", "MutableTree.hooks")
371
self.add_hook('start_commit',
372
"Called before a commit is performed on a tree. The start commit "
373
"hook is able to change the tree before the commit takes place. "
374
"start_commit is called with the breezy.mutabletree.MutableTree "
375
"that the commit is being performed on.", (1, 4))
376
self.add_hook('post_commit',
377
"Called after a commit is performed on a tree. The hook is "
378
"called with a breezy.mutabletree.PostCommitHookParams object. "
379
"The mutable tree the commit was performed on is available via "
380
"the mutable_tree attribute of that object.", (2, 0))
381
self.add_hook('pre_transform',
382
"Called before a tree transform on this tree. The hook is called "
383
"with the tree that is being transformed and the transform.",
385
self.add_hook('post_build_tree',
386
"Called after a completely new tree is built. The hook is "
387
"called with the tree as its only argument.", (2, 5))
388
self.add_hook('post_transform',
389
"Called after a tree transform has been performed on a tree. "
390
"The hook is called with the tree that is being transformed and "
394
# install the default hooks into the MutableTree class.
395
MutableTree.hooks = MutableTreeHooks()
398
class PostCommitHookParams(object):
399
"""Parameters for the post_commit hook.
401
To access the parameters, use the following attributes:
403
* mutable_tree - the MutableTree object
406
def __init__(self, mutable_tree):
407
"""Create the parameters for the post_commit hook."""
408
self.mutable_tree = mutable_tree