/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/mutabletree.py

  • Committer: Jelmer Vernooij
  • Date: 2017-09-01 07:15:43 UTC
  • mfrom: (6770.3.2 py3_test_cleanup)
  • Revision ID: jelmer@jelmer.uk-20170901071543-1t83321xkog9qrxh
Merge lp:~gz/brz/py3_test_cleanup

Show diffs side-by-side

added added

removed removed

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