/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 bzrlib/mutabletree.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""MutableTree object.
18
18
 
19
19
See MutableTree for more details.
20
20
"""
21
21
 
22
 
from . import (
 
22
 
 
23
from bzrlib import (
23
24
    errors,
24
 
    hooks,
25
25
    osutils,
26
 
    trace,
27
26
    tree,
28
27
    )
29
 
 
30
 
 
31
 
 
32
 
class BadReferenceTarget(errors.InternalBzrError):
33
 
 
34
 
    _fmt = "Can't add reference to %(other_tree)s into %(tree)s." \
35
 
           "%(reason)s"
36
 
 
37
 
    def __init__(self, tree, other_tree, reason):
38
 
        self.tree = tree
39
 
        self.other_tree = other_tree
40
 
        self.reason = reason
 
28
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
29
from bzrlib.osutils import splitpath
 
30
from bzrlib.symbol_versioning import DEPRECATED_PARAMETER
 
31
 
 
32
 
 
33
def needs_tree_write_lock(unbound):
 
34
    """Decorate unbound to take out and release a tree_write lock."""
 
35
    def tree_write_locked(self, *args, **kwargs):
 
36
        self.lock_tree_write()
 
37
        try:
 
38
            return unbound(self, *args, **kwargs)
 
39
        finally:
 
40
            self.unlock()
 
41
    tree_write_locked.__doc__ = unbound.__doc__
 
42
    tree_write_locked.__name__ = unbound.__name__
 
43
    return tree_write_locked
41
44
 
42
45
 
43
46
class MutableTree(tree.Tree):
47
50
    context, and will revert if the lock is broken abnormally - but this cannot
48
51
    be guaranteed - depending on the exact implementation of the mutable state.
49
52
 
50
 
    The most common form of Mutable Tree is WorkingTree, see breezy.workingtree.
 
53
    The most common form of Mutable Tree is WorkingTree, see bzrlib.workingtree.
51
54
    For tests we also have MemoryTree which is a MutableTree whose contents are
52
55
    entirely in memory.
53
56
 
54
57
    For now, we are not treating MutableTree as an interface to provide
55
 
    conformance tests for - rather we are testing MemoryTree specifically, and
 
58
    conformance tests for - rather we are testing MemoryTree specifically, and 
56
59
    interface testing implementations of WorkingTree.
57
60
 
58
 
    A mutable tree always has an associated Branch and ControlDir object - the
 
61
    A mutable tree always has an associated Branch and BzrDir object - the
59
62
    branch and bzrdir attributes.
60
63
    """
61
64
 
62
 
    def __init__(self, *args, **kw):
63
 
        super(MutableTree, self).__init__(*args, **kw)
64
 
        # Is this tree on a case-insensitive or case-preserving file-system?
65
 
        # Sub-classes may initialize to False if they detect they are being
66
 
        # used on media which doesn't differentiate the case of names.
67
 
        self.case_sensitive = True
68
 
 
69
 
    def is_control_filename(self, filename):
70
 
        """True if filename is the name of a control file in this tree.
71
 
 
72
 
        :param filename: A filename within the tree. This is a relative path
73
 
            from the root of this tree.
74
 
 
75
 
        This is true IF and ONLY IF the filename is part of the meta data
76
 
        that bzr controls in this tree. I.E. a random .bzr directory placed
77
 
        on disk will not be a control file for this tree.
78
 
        """
79
 
        raise NotImplementedError(self.is_control_filename)
80
 
 
 
65
    @needs_tree_write_lock
81
66
    def add(self, files, ids=None, kinds=None):
82
67
        """Add paths to the set of versioned paths.
83
68
 
84
69
        Note that the command line normally calls smart_add instead,
85
70
        which can automatically recurse.
86
71
 
87
 
        This adds the files to the tree, so that they will be
 
72
        This adds the files to the inventory, so that they will be
88
73
        recorded by the next commit.
89
74
 
90
75
        :param files: List of paths to add, relative to the base of the tree.
96
81
 
97
82
        TODO: Perhaps callback with the ids and paths as they're added.
98
83
        """
99
 
        if isinstance(files, str):
100
 
            # XXX: Passing a single string is inconsistent and should be
101
 
            # deprecated.
102
 
            if not (ids is None or isinstance(ids, bytes)):
103
 
                raise AssertionError()
104
 
            if not (kinds is None or isinstance(kinds, str)):
105
 
                raise AssertionError()
 
84
        if isinstance(files, basestring):
 
85
            assert(ids is None or isinstance(ids, basestring))
 
86
            assert(kinds is None or isinstance(kinds, basestring))
106
87
            files = [files]
107
88
            if ids is not None:
108
89
                ids = [ids]
114
95
        if ids is None:
115
96
            ids = [None] * len(files)
116
97
        else:
117
 
            if not (len(ids) == len(files)):
118
 
                raise AssertionError()
 
98
            assert(len(ids) == len(files))
 
99
            ids = [osutils.safe_file_id(file_id) for file_id in ids]
 
100
 
119
101
        if kinds is None:
120
102
            kinds = [None] * len(files)
121
 
        elif not len(kinds) == len(files):
122
 
            raise AssertionError()
123
 
        with self.lock_tree_write():
124
 
            for f in files:
125
 
                # generic constraint checks:
126
 
                if self.is_control_filename(f):
127
 
                    raise errors.ForbiddenControlFileError(filename=f)
128
 
                fp = osutils.splitpath(f)
129
 
            # fill out file kinds for all files [not needed when we stop
130
 
            # caring about the instantaneous file kind within a uncommmitted tree
131
 
            #
132
 
            self._gather_kinds(files, kinds)
133
 
            self._add(files, ids, kinds)
 
103
        else:
 
104
            assert(len(kinds) == len(files))
 
105
        for f in files:
 
106
            # generic constraint checks:
 
107
            if self.is_control_filename(f):
 
108
                raise errors.ForbiddenControlFileError(filename=f)
 
109
            fp = splitpath(f)
 
110
        # fill out file kinds for all files [not needed when we stop 
 
111
        # caring about the instantaneous file kind within a uncommmitted tree
 
112
        #
 
113
        self._gather_kinds(files, kinds)
 
114
        self._add(files, ids, kinds)
134
115
 
135
116
    def add_reference(self, sub_tree):
136
 
        """Add a TreeReference to the tree, pointing at sub_tree.
137
 
 
138
 
        :param sub_tree: subtree to add.
139
 
        """
 
117
        """Add a TreeReference to the tree, pointing at sub_tree"""
140
118
        raise errors.UnsupportedOperation(self.add_reference, self)
141
119
 
 
120
    def _add_reference(self, sub_tree):
 
121
        """Standard add_reference implementation, for use by subclasses"""
 
122
        try:
 
123
            sub_tree_path = self.relpath(sub_tree.basedir)
 
124
        except errors.PathNotChild:
 
125
            raise errors.BadReferenceTarget(self, sub_tree,
 
126
                                            'Target not inside tree.')
 
127
        sub_tree_id = sub_tree.get_root_id()
 
128
        if sub_tree_id == self.get_root_id():
 
129
            raise errors.BadReferenceTarget(self, sub_tree,
 
130
                                     'Trees have the same root id.')
 
131
        if sub_tree_id in self.inventory:
 
132
            raise errors.BadReferenceTarget(self, sub_tree,
 
133
                                            'Root id already present in tree')
 
134
        self._add([sub_tree_path], [sub_tree_id], ['tree-reference'])
 
135
 
142
136
    def _add(self, files, ids, kinds):
143
137
        """Helper function for add - updates the inventory.
144
138
 
149
143
        """
150
144
        raise NotImplementedError(self._add)
151
145
 
152
 
    def commit(self, message=None, revprops=None, *args, **kwargs):
 
146
    @needs_tree_write_lock
 
147
    def apply_inventory_delta(self, changes):
 
148
        """Apply changes to the inventory as an atomic operation.
 
149
 
 
150
        The argument is a set of changes to apply.  It must describe a
 
151
        valid result, but the order is not important.  Specifically,
 
152
        intermediate stages *may* be invalid, such as when two files
 
153
        swap names.
 
154
 
 
155
        The changes should be structured as a list of tuples, of the form
 
156
        (old_path, new_path, file_id, new_entry).  For creation, old_path
 
157
        must be None.  For deletion, new_path and new_entry must be None.
 
158
        file_id is always non-None.  For renames and other mutations, all
 
159
        values must be non-None.
 
160
 
 
161
        If the new_entry is a directory, its children should be an empty
 
162
        dict.  Children are handled by apply_inventory_delta itself.
 
163
 
 
164
        :param changes: A list of tuples for the change to apply:
 
165
            [(old_path, new_path, file_id, new_inventory_entry), ...]
 
166
        """
 
167
        self.flush()
 
168
        inv = self.inventory
 
169
        children = {}
 
170
        for old_path, file_id in sorted(((op, f) for op, np, f, e in changes
 
171
                                        if op is not None), reverse=True):
 
172
            if file_id not in inv:
 
173
                continue
 
174
            children[file_id] = getattr(inv[file_id], 'children', {})
 
175
            inv.remove_recursive_id(file_id)
 
176
        for new_path, new_entry in sorted((np, e) for op, np, f, e in
 
177
                                          changes if np is not None):
 
178
            if getattr(new_entry, 'children', None) is not None:
 
179
                new_entry.children = children.get(new_entry.file_id, {})
 
180
            inv.add(new_entry)
 
181
        self._write_inventory(inv)
 
182
 
 
183
    @needs_write_lock
 
184
    def commit(self, message=None, revprops=None, *args,
 
185
               **kwargs):
153
186
        # avoid circular imports
154
 
        from breezy import commit
155
 
        possible_master_transports = []
156
 
        with self.lock_write():
157
 
            revprops = commit.Commit.update_revprops(
158
 
                revprops,
159
 
                self.branch,
160
 
                kwargs.pop('authors', None),
161
 
                kwargs.get('local', False),
162
 
                possible_master_transports)
163
 
            # args for wt.commit start at message from the Commit.commit method,
164
 
            args = (message, ) + args
165
 
            for hook in MutableTree.hooks['start_commit']:
166
 
                hook(self)
167
 
            committed_id = commit.Commit().commit(working_tree=self,
168
 
                                                  revprops=revprops,
169
 
                                                  possible_master_transports=possible_master_transports,
170
 
                                                  *args, **kwargs)
171
 
            post_hook_params = PostCommitHookParams(self)
172
 
            for hook in MutableTree.hooks['post_commit']:
173
 
                hook(post_hook_params)
174
 
            return committed_id
 
187
        from bzrlib import commit
 
188
        if revprops is None:
 
189
            revprops = {}
 
190
        if not 'branch-nick' in revprops:
 
191
            revprops['branch-nick'] = self.branch.nick
 
192
        # args for wt.commit start at message from the Commit.commit method,
 
193
        args = (message, ) + args
 
194
        committed_id = commit.Commit().commit(working_tree=self,
 
195
            revprops=revprops, *args, **kwargs)
 
196
        return committed_id
175
197
 
176
198
    def _gather_kinds(self, files, kinds):
177
199
        """Helper function for add - sets the entries of kinds."""
178
200
        raise NotImplementedError(self._gather_kinds)
179
201
 
180
 
    def has_changes(self, _from_tree=None):
181
 
        """Quickly check that the tree contains at least one commitable change.
182
 
 
183
 
        :param _from_tree: tree to compare against to find changes (default to
184
 
            the basis tree and is intended to be used by tests).
185
 
 
186
 
        :return: True if a change is found. False otherwise
187
 
        """
188
 
        with self.lock_read():
189
 
            # Check pending merges
190
 
            if len(self.get_parent_ids()) > 1:
191
 
                return True
192
 
            if _from_tree is None:
193
 
                _from_tree = self.basis_tree()
194
 
            changes = self.iter_changes(_from_tree)
195
 
            if self.supports_symlinks():
196
 
                # Fast path for has_changes.
197
 
                try:
198
 
                    change = next(changes)
199
 
                    # Exclude root (talk about black magic... --vila 20090629)
200
 
                    if change.parent_id == (None, None):
201
 
                        change = next(changes)
202
 
                    return True
203
 
                except StopIteration:
204
 
                    # No changes
205
 
                    return False
206
 
            else:
207
 
                # Slow path for has_changes.
208
 
                # Handle platforms that do not support symlinks in the
209
 
                # conditional below. This is slower than the try/except
210
 
                # approach below that but we don't have a choice as we
211
 
                # need to be sure that all symlinks are removed from the
212
 
                # entire changeset. This is because in platforms that
213
 
                # do not support symlinks, they show up as None in the
214
 
                # working copy as compared to the repository.
215
 
                # Also, exclude root as mention in the above fast path.
216
 
                changes = filter(
217
 
                    lambda c: c[6][0] != 'symlink' and c[4] != (None, None),
218
 
                    changes)
219
 
                try:
220
 
                    next(iter(changes))
221
 
                except StopIteration:
222
 
                    return False
223
 
                return True
224
 
 
225
 
    def check_changed_or_out_of_date(self, strict, opt_name,
226
 
                                     more_error, more_warning):
227
 
        """Check the tree for uncommitted changes and branch synchronization.
228
 
 
229
 
        If strict is None and not set in the config files, a warning is issued.
230
 
        If strict is True, an error is raised.
231
 
        If strict is False, no checks are done and no warning is issued.
232
 
 
233
 
        :param strict: True, False or None, searched in branch config if None.
234
 
 
235
 
        :param opt_name: strict option name to search in config file.
236
 
 
237
 
        :param more_error: Details about how to avoid the check.
238
 
 
239
 
        :param more_warning: Details about what is happening.
240
 
        """
241
 
        with self.lock_read():
242
 
            if strict is None:
243
 
                strict = self.branch.get_config_stack().get(opt_name)
244
 
            if strict is not False:
245
 
                err_class = None
246
 
                if (self.has_changes()):
247
 
                    err_class = errors.UncommittedChanges
248
 
                elif self.last_revision() != self.branch.last_revision():
249
 
                    # The tree has lost sync with its branch, there is little
250
 
                    # chance that the user is aware of it but he can still
251
 
                    # force the action with --no-strict
252
 
                    err_class = errors.OutOfDateTree
253
 
                if err_class is not None:
254
 
                    if strict is None:
255
 
                        err = err_class(self, more=more_warning)
256
 
                        # We don't want to interrupt the user if he expressed
257
 
                        # no preference about strict.
258
 
                        trace.warning('%s', err._format())
259
 
                    else:
260
 
                        err = err_class(self, more=more_error)
261
 
                        raise err
262
 
 
 
202
    @needs_read_lock
263
203
    def last_revision(self):
264
204
        """Return the revision id of the last commit performed in this tree.
265
205
 
266
206
        In early tree formats the result of last_revision is the same as the
267
207
        branch last_revision, but that is no longer the case for modern tree
268
208
        formats.
269
 
 
 
209
        
270
210
        last_revision returns the left most parent id, or None if there are no
271
211
        parents.
272
212
 
289
229
    def lock_write(self):
290
230
        """Lock the tree and its branch. This allows mutating calls to be made.
291
231
 
292
 
        Some mutating methods will take out implicit write locks, but in
 
232
        Some mutating methods will take out implicit write locks, but in 
293
233
        general you should always obtain a write lock before calling mutating
294
234
        methods on a tree.
295
235
        """
296
236
        raise NotImplementedError(self.lock_write)
297
237
 
 
238
    @needs_write_lock
298
239
    def mkdir(self, path, file_id=None):
299
240
        """Create a directory in the tree. if file_id is None, one is assigned.
300
241
 
304
245
        """
305
246
        raise NotImplementedError(self.mkdir)
306
247
 
307
 
    def _observed_sha1(self, path, sha_and_stat):
308
 
        """Tell the tree we have observed a paths sha1.
309
 
 
310
 
        The intent of this function is to allow trees that have a hashcache to
311
 
        update the hashcache during commit. If the observed file is too new
312
 
        (based on the stat_value) to be safely hash-cached the tree will ignore
313
 
        it.
314
 
 
315
 
        The default implementation does nothing.
316
 
 
317
 
        :param path: The file path
318
 
        :param sha_and_stat: The sha 1 and stat result observed.
319
 
        :return: None
320
 
        """
321
 
 
322
 
    def put_file_bytes_non_atomic(self, path, bytes):
323
 
        """Update the content of a file in the tree.
324
 
 
325
 
        Note that the file is written in-place rather than being
326
 
        written to a temporary location and renamed. As a consequence,
327
 
        readers can potentially see the file half-written.
328
 
 
329
 
        :param file_id: file-id of the file
330
 
        :param bytes: the new file contents
331
 
        """
332
 
        raise NotImplementedError(self.put_file_bytes_non_atomic)
333
 
 
334
 
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
335
 
        """Set the parents ids of the working tree.
336
 
 
337
 
        :param revision_ids: A list of revision_ids.
338
 
        """
339
 
        raise NotImplementedError(self.set_parent_ids)
340
 
 
341
248
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
342
249
        """Set the parents of the working tree.
343
250
 
344
 
        :param parents_list: A list of (revision_id, tree) tuples.
 
251
        :param parents_list: A list of (revision_id, tree) tuples. 
345
252
            If tree is None, then that element is treated as an unreachable
346
253
            parent tree - i.e. a ghost.
347
254
        """
348
255
        raise NotImplementedError(self.set_parent_trees)
349
 
 
350
 
    def smart_add(self, file_list, recurse=True, action=None, save=True):
351
 
        """Version file_list, optionally recursing into directories.
352
 
 
353
 
        This is designed more towards DWIM for humans than API clarity.
354
 
        For the specific behaviour see the help for cmd_add().
355
 
 
356
 
        :param file_list: List of zero or more paths.  *NB: these are
357
 
            interpreted relative to the process cwd, not relative to the
358
 
            tree.*  (Add and most other tree methods use tree-relative
359
 
            paths.)
360
 
        :param action: A reporter to be called with the working tree, parent_ie,
361
 
            path and kind of the path being added. It may return a file_id if
362
 
            a specific one should be used.
363
 
        :param save: Save the changes after completing the adds. If False
364
 
            this provides dry-run functionality by doing the add and not saving
365
 
            the changes.
366
 
        :return: A tuple - files_added, ignored_files. files_added is the count
367
 
            of added files, and ignored_files is a dict mapping files that were
368
 
            ignored to the rule that caused them to be ignored.
369
 
        """
370
 
        raise NotImplementedError(self.smart_add)
371
 
 
372
 
    def rename_one(self, from_rel, to_rel, after=False):
373
 
        """Rename one file.
374
 
 
375
 
        This can change the directory or the filename or both.
376
 
 
377
 
        rename_one has several 'modes' to work. First, it can rename a physical
378
 
        file and change the file_id. That is the normal mode. Second, it can
379
 
        only change the file_id without touching any physical file.
380
 
 
381
 
        rename_one uses the second mode if 'after == True' and 'to_rel' is
382
 
        either not versioned or newly added, and present in the working tree.
383
 
 
384
 
        rename_one uses the second mode if 'after == False' and 'from_rel' is
385
 
        versioned but no longer in the working tree, and 'to_rel' is not
386
 
        versioned but present in the working tree.
387
 
 
388
 
        rename_one uses the first mode if 'after == False' and 'from_rel' is
389
 
        versioned and present in the working tree, and 'to_rel' is not
390
 
        versioned and not present in the working tree.
391
 
 
392
 
        Everything else results in an error.
393
 
        """
394
 
        raise NotImplementedError(self.rename_one)
395
 
 
396
 
    def copy_one(self, from_rel, to_rel):
397
 
        """Copy one file or directory.
398
 
 
399
 
        This can change the directory or the filename or both.
400
 
 
401
 
        """
402
 
        raise NotImplementedError(self.copy_one)
403
 
 
404
 
    def transform(self, pb=None):
405
 
        """Return a transform object for use with this tree."""
406
 
        raise NotImplementedError(self.transform)
407
 
 
408
 
 
409
 
class MutableTreeHooks(hooks.Hooks):
410
 
    """A dictionary mapping a hook name to a list of callables for mutabletree
411
 
    hooks.
412
 
    """
413
 
 
414
 
    def __init__(self):
415
 
        """Create the default hooks.
416
 
 
417
 
        """
418
 
        hooks.Hooks.__init__(self, "breezy.mutabletree", "MutableTree.hooks")
419
 
        self.add_hook('start_commit',
420
 
                      "Called before a commit is performed on a tree. The start commit "
421
 
                      "hook is able to change the tree before the commit takes place. "
422
 
                      "start_commit is called with the breezy.mutabletree.MutableTree "
423
 
                      "that the commit is being performed on.", (1, 4))
424
 
        self.add_hook('post_commit',
425
 
                      "Called after a commit is performed on a tree. The hook is "
426
 
                      "called with a breezy.mutabletree.PostCommitHookParams object. "
427
 
                      "The mutable tree the commit was performed on is available via "
428
 
                      "the mutable_tree attribute of that object.", (2, 0))
429
 
        self.add_hook('pre_transform',
430
 
                      "Called before a tree transform on this tree. The hook is called "
431
 
                      "with the tree that is being transformed and the transform.",
432
 
                      (2, 5))
433
 
        self.add_hook('post_build_tree',
434
 
                      "Called after a completely new tree is built. The hook is "
435
 
                      "called with the tree as its only argument.", (2, 5))
436
 
        self.add_hook('post_transform',
437
 
                      "Called after a tree transform has been performed on a tree. "
438
 
                      "The hook is called with the tree that is being transformed and "
439
 
                      "the transform.",
440
 
                      (2, 5))
441
 
 
442
 
 
443
 
# install the default hooks into the MutableTree class.
444
 
MutableTree.hooks = MutableTreeHooks()
445
 
 
446
 
 
447
 
class PostCommitHookParams(object):
448
 
    """Parameters for the post_commit hook.
449
 
 
450
 
    To access the parameters, use the following attributes:
451
 
 
452
 
    * mutable_tree - the MutableTree object
453
 
    """
454
 
 
455
 
    def __init__(self, mutable_tree):
456
 
        """Create the parameters for the post_commit hook."""
457
 
        self.mutable_tree = mutable_tree