/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: 2019-06-03 23:48:08 UTC
  • mfrom: (7316 work)
  • mto: This revision was merged to the branch mainline in revision 7328.
  • Revision ID: jelmer@jelmer.uk-20190603234808-15yk5c7054tj8e2b
Merge trunk.

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