1
# Copyright (C) 2006, 2007 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
"""MutableTree object.
 
 
19
See MutableTree for more details.
 
 
23
from bzrlib.lazy_import import lazy_import
 
 
24
lazy_import(globals(), """
 
 
32
from bzrlib.osutils import dirname
 
 
33
from bzrlib.revisiontree import RevisionTree
 
 
34
from bzrlib.trace import mutter, warning
 
 
42
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
 
43
from bzrlib.osutils import splitpath
 
 
44
from bzrlib.symbol_versioning import DEPRECATED_PARAMETER
 
 
47
def needs_tree_write_lock(unbound):
 
 
48
    """Decorate unbound to take out and release a tree_write lock."""
 
 
49
    def tree_write_locked(self, *args, **kwargs):
 
 
50
        self.lock_tree_write()
 
 
52
            return unbound(self, *args, **kwargs)
 
 
55
    tree_write_locked.__doc__ = unbound.__doc__
 
 
56
    tree_write_locked.__name__ = unbound.__name__
 
 
57
    return tree_write_locked
 
 
60
class MutableTree(tree.Tree):
 
 
61
    """A MutableTree is a specialisation of Tree which is able to be mutated.
 
 
63
    Generally speaking these mutations are only possible within a lock_write
 
 
64
    context, and will revert if the lock is broken abnormally - but this cannot
 
 
65
    be guaranteed - depending on the exact implementation of the mutable state.
 
 
67
    The most common form of Mutable Tree is WorkingTree, see bzrlib.workingtree.
 
 
68
    For tests we also have MemoryTree which is a MutableTree whose contents are
 
 
71
    For now, we are not treating MutableTree as an interface to provide
 
 
72
    conformance tests for - rather we are testing MemoryTree specifically, and 
 
 
73
    interface testing implementations of WorkingTree.
 
 
75
    A mutable tree always has an associated Branch and BzrDir object - the
 
 
76
    branch and bzrdir attributes.
 
 
79
    @needs_tree_write_lock
 
 
80
    def add(self, files, ids=None, kinds=None):
 
 
81
        """Add paths to the set of versioned paths.
 
 
83
        Note that the command line normally calls smart_add instead,
 
 
84
        which can automatically recurse.
 
 
86
        This adds the files to the inventory, so that they will be
 
 
87
        recorded by the next commit.
 
 
89
        :param files: List of paths to add, relative to the base of the tree.
 
 
90
        :param ids: If set, use these instead of automatically generated ids.
 
 
91
            Must be the same length as the list of files, but may
 
 
92
            contain None for ids that are to be autogenerated.
 
 
93
        :param kinds: Optional parameter to specify the kinds to be used for
 
 
96
        TODO: Perhaps callback with the ids and paths as they're added.
 
 
98
        if isinstance(files, basestring):
 
 
99
            # XXX: Passing a single string is inconsistent and should be
 
 
101
            if not (ids is None or isinstance(ids, basestring)):
 
 
102
                raise AssertionError()
 
 
103
            if not (kinds is None or isinstance(kinds, basestring)):
 
 
104
                raise AssertionError()
 
 
108
            if kinds is not None:
 
 
111
        files = [path.strip('/') for path in files]
 
 
114
            ids = [None] * len(files)
 
 
116
            if not (len(ids) == len(files)):
 
 
117
                raise AssertionError()
 
 
119
            kinds = [None] * len(files)
 
 
120
        elif not len(kinds) == len(files):
 
 
121
            raise AssertionError()
 
 
123
            # generic constraint checks:
 
 
124
            if self.is_control_filename(f):
 
 
125
                raise errors.ForbiddenControlFileError(filename=f)
 
 
127
        # fill out file kinds for all files [not needed when we stop 
 
 
128
        # caring about the instantaneous file kind within a uncommmitted tree
 
 
130
        self._gather_kinds(files, kinds)
 
 
131
        self._add(files, ids, kinds)
 
 
133
    def add_reference(self, sub_tree):
 
 
134
        """Add a TreeReference to the tree, pointing at sub_tree"""
 
 
135
        raise errors.UnsupportedOperation(self.add_reference, self)
 
 
137
    def _add_reference(self, sub_tree):
 
 
138
        """Standard add_reference implementation, for use by subclasses"""
 
 
140
            sub_tree_path = self.relpath(sub_tree.basedir)
 
 
141
        except errors.PathNotChild:
 
 
142
            raise errors.BadReferenceTarget(self, sub_tree,
 
 
143
                                            'Target not inside tree.')
 
 
144
        sub_tree_id = sub_tree.get_root_id()
 
 
145
        if sub_tree_id == self.get_root_id():
 
 
146
            raise errors.BadReferenceTarget(self, sub_tree,
 
 
147
                                     'Trees have the same root id.')
 
 
148
        if sub_tree_id in self.inventory:
 
 
149
            raise errors.BadReferenceTarget(self, sub_tree,
 
 
150
                                            'Root id already present in tree')
 
 
151
        self._add([sub_tree_path], [sub_tree_id], ['tree-reference'])
 
 
153
    def _add(self, files, ids, kinds):
 
 
154
        """Helper function for add - updates the inventory.
 
 
156
        :param files: sequence of pathnames, relative to the tree root
 
 
157
        :param ids: sequence of suggested ids for the files (may be None)
 
 
158
        :param kinds: sequence of  inventory kinds of the files (i.e. may
 
 
159
            contain "tree-reference")
 
 
161
        raise NotImplementedError(self._add)
 
 
163
    @needs_tree_write_lock
 
 
164
    def apply_inventory_delta(self, changes):
 
 
165
        """Apply changes to the inventory as an atomic operation.
 
 
167
        :param changes: An inventory delta to apply to the working tree's
 
 
170
        :seealso Inventory.apply_delta: For details on the changes parameter.
 
 
174
        inv.apply_delta(changes)
 
 
175
        self._write_inventory(inv)
 
 
178
    def commit(self, message=None, revprops=None, *args,
 
 
180
        # avoid circular imports
 
 
181
        from bzrlib import commit
 
 
184
        if not 'branch-nick' in revprops:
 
 
185
            revprops['branch-nick'] = self.branch.nick
 
 
186
        author = kwargs.pop('author', None)
 
 
187
        if author is not None:
 
 
188
            if 'author' in revprops:
 
 
189
                # XXX: maybe we should just accept one of them?
 
 
190
                raise AssertionError('author property given twice')
 
 
191
            revprops['author'] = author
 
 
192
        # args for wt.commit start at message from the Commit.commit method,
 
 
193
        args = (message, ) + args
 
 
194
        for hook in MutableTree.hooks['start_commit']:
 
 
196
        committed_id = commit.Commit().commit(working_tree=self,
 
 
197
            revprops=revprops, *args, **kwargs)
 
 
200
    def _gather_kinds(self, files, kinds):
 
 
201
        """Helper function for add - sets the entries of kinds."""
 
 
202
        raise NotImplementedError(self._gather_kinds)
 
 
204
    def get_file_with_stat(self, file_id, path=None):
 
 
205
        """Get a file handle and stat object for file_id.
 
 
207
        The default implementation returns (self.get_file, None) for backwards
 
 
210
        :param file_id: The file id to read.
 
 
211
        :param path: The path of the file, if it is known.
 
 
212
        :return: A tuple (file_handle, stat_value_or_None). If the tree has
 
 
213
            no stat facility, or need for a stat cache feedback during commit,
 
 
214
            it may return None for the second element of the tuple.
 
 
216
        return (self.get_file(file_id, path), None)
 
 
219
    def last_revision(self):
 
 
220
        """Return the revision id of the last commit performed in this tree.
 
 
222
        In early tree formats the result of last_revision is the same as the
 
 
223
        branch last_revision, but that is no longer the case for modern tree
 
 
226
        last_revision returns the left most parent id, or None if there are no
 
 
229
        last_revision was deprecated as of 0.11. Please use get_parent_ids
 
 
232
        raise NotImplementedError(self.last_revision)
 
 
234
    def lock_tree_write(self):
 
 
235
        """Lock the working tree for write, and the branch for read.
 
 
237
        This is useful for operations which only need to mutate the working
 
 
238
        tree. Taking out branch write locks is a relatively expensive process
 
 
239
        and may fail if the branch is on read only media. So branch write locks
 
 
240
        should only be taken out when we are modifying branch data - such as in
 
 
241
        operations like commit, pull, uncommit and update.
 
 
243
        raise NotImplementedError(self.lock_tree_write)
 
 
245
    def lock_write(self):
 
 
246
        """Lock the tree and its branch. This allows mutating calls to be made.
 
 
248
        Some mutating methods will take out implicit write locks, but in 
 
 
249
        general you should always obtain a write lock before calling mutating
 
 
252
        raise NotImplementedError(self.lock_write)
 
 
255
    def mkdir(self, path, file_id=None):
 
 
256
        """Create a directory in the tree. if file_id is None, one is assigned.
 
 
258
        :param path: A unicode file path.
 
 
259
        :param file_id: An optional file-id.
 
 
260
        :return: the file id of the new directory.
 
 
262
        raise NotImplementedError(self.mkdir)
 
 
264
    def _observed_sha1(self, file_id, path, (sha1, stat_value)):
 
 
265
        """Tell the tree we have observed a paths sha1.
 
 
267
        The intent of this function is to allow trees that have a hashcache to
 
 
268
        update the hashcache during commit. If the observed file is too new
 
 
269
        (based on the stat_value) to be safely hash-cached the tree will ignore
 
 
272
        The default implementation does nothing.
 
 
274
        :param file_id: The file id
 
 
275
        :param path: The file path
 
 
276
        :param sha1: The sha 1 that was observed.
 
 
277
        :param stat_value: A stat result for the file the sha1 was read from.
 
 
282
    def put_file_bytes_non_atomic(self, file_id, bytes):
 
 
283
        """Update the content of a file in the tree.
 
 
285
        Note that the file is written in-place rather than being
 
 
286
        written to a temporary location and renamed. As a consequence,
 
 
287
        readers can potentially see the file half-written.
 
 
289
        :param file_id: file-id of the file
 
 
290
        :param bytes: the new file contents
 
 
292
        raise NotImplementedError(self.put_file_bytes_non_atomic)
 
 
294
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
 
 
295
        """Set the parents ids of the working tree.
 
 
297
        :param revision_ids: A list of revision_ids.
 
 
299
        raise NotImplementedError(self.set_parent_ids)
 
 
301
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
 
 
302
        """Set the parents of the working tree.
 
 
304
        :param parents_list: A list of (revision_id, tree) tuples. 
 
 
305
            If tree is None, then that element is treated as an unreachable
 
 
306
            parent tree - i.e. a ghost.
 
 
308
        raise NotImplementedError(self.set_parent_trees)
 
 
310
    @needs_tree_write_lock
 
 
311
    def smart_add(self, file_list, recurse=True, action=None, save=True):
 
 
312
        """Version file_list, optionally recursing into directories.
 
 
314
        This is designed more towards DWIM for humans than API clarity.
 
 
315
        For the specific behaviour see the help for cmd_add().
 
 
317
        :param action: A reporter to be called with the inventory, parent_ie,
 
 
318
            path and kind of the path being added. It may return a file_id if 
 
 
319
            a specific one should be used.
 
 
320
        :param save: Save the inventory after completing the adds. If False
 
 
321
            this provides dry-run functionality by doing the add and not saving
 
 
323
        :return: A tuple - files_added, ignored_files. files_added is the count
 
 
324
            of added files, and ignored_files is a dict mapping files that were
 
 
325
            ignored to the rule that caused them to be ignored.
 
 
327
        # not in an inner loop; and we want to remove direct use of this,
 
 
328
        # so here as a reminder for now. RBC 20070703
 
 
329
        from bzrlib.inventory import InventoryEntry
 
 
331
            action = add.AddAction()
 
 
334
            # no paths supplied: add the entire tree.
 
 
336
        # mutter("smart add of %r")
 
 
343
        # validate user file paths and convert all paths to tree 
 
 
344
        # relative : it's cheaper to make a tree relative path an abspath
 
 
345
        # than to convert an abspath to tree relative.
 
 
346
        for filepath in file_list:
 
 
347
            rf = _FastPath(self.relpath(filepath))
 
 
348
            # validate user parameters. Our recursive code avoids adding new files
 
 
349
            # that need such validation 
 
 
350
            if self.is_control_filename(rf.raw_path):
 
 
351
                raise errors.ForbiddenControlFileError(filename=rf.raw_path)
 
 
353
            abspath = self.abspath(rf.raw_path)
 
 
354
            kind = osutils.file_kind(abspath)
 
 
355
            if kind == 'directory':
 
 
356
                # schedule the dir for scanning
 
 
359
                if not InventoryEntry.versionable_kind(kind):
 
 
360
                    raise errors.BadFileKindError(filename=abspath, kind=kind)
 
 
361
            # ensure the named path is added, so that ignore rules in the later directory
 
 
363
            # we dont have a parent ie known yet.: use the relatively slower inventory 
 
 
365
            versioned = inv.has_filename(rf.raw_path)
 
 
368
            added.extend(_add_one_and_parent(self, inv, None, rf, kind, action))
 
 
371
            # no need to walk any directories at all.
 
 
372
            if len(added) > 0 and save:
 
 
373
                self._write_inventory(inv)
 
 
374
            return added, ignored
 
 
376
        # only walk the minimal parents needed: we have user_dirs to override
 
 
380
        is_inside = osutils.is_inside_or_parent_of_any
 
 
381
        for path in sorted(user_dirs):
 
 
382
            if (prev_dir is None or not is_inside([prev_dir], path.raw_path)):
 
 
383
                dirs_to_add.append((path, None))
 
 
384
            prev_dir = path.raw_path
 
 
386
        # dirs_to_add is initialised to a list of directories, but as we scan
 
 
387
        # directories we append files to it.
 
 
388
        # XXX: We should determine kind of files when we scan them rather than
 
 
389
        # adding to this list. RBC 20070703
 
 
390
        for directory, parent_ie in dirs_to_add:
 
 
391
            # directory is tree-relative
 
 
392
            abspath = self.abspath(directory.raw_path)
 
 
394
            # get the contents of this directory.
 
 
396
            # find the kind of the path being added.
 
 
397
            kind = osutils.file_kind(abspath)
 
 
399
            if not InventoryEntry.versionable_kind(kind):
 
 
400
                warning("skipping %s (can't add file of kind '%s')", abspath, kind)
 
 
403
            if parent_ie is not None:
 
 
404
                versioned = directory.base_path in parent_ie.children
 
 
406
                # without the parent ie, use the relatively slower inventory 
 
 
408
                versioned = inv.has_filename(directory.raw_path)
 
 
410
            if kind == 'directory':
 
 
412
                    sub_branch = bzrdir.BzrDir.open(abspath)
 
 
414
                except errors.NotBranchError:
 
 
416
                except errors.UnsupportedFormatError:
 
 
421
            if directory.raw_path == '':
 
 
422
                # mutter("tree root doesn't need to be added")
 
 
426
                # mutter("%r is already versioned", abspath)
 
 
428
                # XXX: This is wrong; people *might* reasonably be trying to add
 
 
429
                # subtrees as subtrees.  This should probably only be done in formats 
 
 
430
                # which can represent subtrees, and even then perhaps only when
 
 
431
                # the user asked to add subtrees.  At the moment you can add them
 
 
432
                # specially through 'join --reference', which is perhaps
 
 
433
                # reasonable: adding a new reference is a special operation and
 
 
434
                # can have a special behaviour.  mbp 20070306
 
 
435
                mutter("%r is a nested bzr tree", abspath)
 
 
437
                _add_one(self, inv, parent_ie, directory, kind, action)
 
 
438
                added.append(directory.raw_path)
 
 
440
            if kind == 'directory' and not sub_tree:
 
 
441
                if parent_ie is not None:
 
 
443
                    this_ie = parent_ie.children[directory.base_path]
 
 
445
                    # without the parent ie, use the relatively slower inventory 
 
 
447
                    this_id = inv.path2id(directory.raw_path)
 
 
451
                        this_ie = inv[this_id]
 
 
453
                for subf in sorted(os.listdir(abspath)):
 
 
454
                    # here we could use TreeDirectory rather than 
 
 
455
                    # string concatenation.
 
 
456
                    subp = osutils.pathjoin(directory.raw_path, subf)
 
 
457
                    # TODO: is_control_filename is very slow. Make it faster. 
 
 
458
                    # TreeDirectory.is_control_filename could also make this 
 
 
459
                    # faster - its impossible for a non root dir to have a 
 
 
461
                    if self.is_control_filename(subp):
 
 
462
                        mutter("skip control directory %r", subp)
 
 
463
                    elif subf in this_ie.children:
 
 
464
                        # recurse into this already versioned subdir.
 
 
465
                        dirs_to_add.append((_FastPath(subp, subf), this_ie))
 
 
467
                        # user selection overrides ignoes
 
 
468
                        # ignore while selecting files - if we globbed in the
 
 
469
                        # outer loop we would ignore user files.
 
 
470
                        ignore_glob = self.is_ignored(subp)
 
 
471
                        if ignore_glob is not None:
 
 
472
                            # mutter("skip ignored sub-file %r", subp)
 
 
473
                            ignored.setdefault(ignore_glob, []).append(subp)
 
 
475
                            #mutter("queue to add sub-file %r", subp)
 
 
476
                            dirs_to_add.append((_FastPath(subp, subf), this_ie))
 
 
480
                self._write_inventory(inv)
 
 
482
                self.read_working_inventory()
 
 
483
        return added, ignored
 
 
485
    def update_basis_by_delta(self, new_revid, delta):
 
 
486
        """Update the parents of this tree after a commit.
 
 
488
        This gives the tree one parent, with revision id new_revid. The
 
 
489
        inventory delta is applied to the current basis tree to generate the
 
 
490
        inventory for the parent new_revid, and all other parent trees are
 
 
493
        All the changes in the delta should be changes synchronising the basis
 
 
494
        tree with some or all of the working tree, with a change to a directory
 
 
495
        requiring that its contents have been recursively included. That is,
 
 
496
        this is not a general purpose tree modification routine, but a helper
 
 
497
        for commit which is not required to handle situations that do not arise
 
 
500
        :param new_revid: The new revision id for the trees parent.
 
 
501
        :param delta: An inventory delta (see apply_inventory_delta) describing
 
 
502
            the changes from the current left most parent revision to new_revid.
 
 
504
        # if the tree is updated by a pull to the branch, as happens in
 
 
505
        # WorkingTree2, when there was no separation between branch and tree,
 
 
506
        # then just clear merges, efficiency is not a concern for now as this
 
 
507
        # is legacy environments only, and they are slow regardless.
 
 
508
        if self.last_revision() == new_revid:
 
 
509
            self.set_parent_ids([new_revid])
 
 
511
        # generic implementation based on Inventory manipulation. See
 
 
512
        # WorkingTree classes for optimised versions for specific format trees.
 
 
513
        basis = self.basis_tree()
 
 
515
        inventory = basis.inventory
 
 
517
        inventory.apply_delta(delta)
 
 
518
        rev_tree = RevisionTree(self.branch.repository, inventory, new_revid)
 
 
519
        self.set_parent_trees([(new_revid, rev_tree)])
 
 
522
class MutableTreeHooks(hooks.Hooks):
 
 
523
    """A dictionary mapping a hook name to a list of callables for mutabletree 
 
 
528
        """Create the default hooks.
 
 
531
        hooks.Hooks.__init__(self)
 
 
532
        # Invoked before a commit is done in a tree. New in 1.4
 
 
533
        self['start_commit'] = []
 
 
536
# install the default hooks into the MutableTree class.
 
 
537
MutableTree.hooks = MutableTreeHooks()
 
 
540
class _FastPath(object):
 
 
541
    """A path object with fast accessors for things like basename."""
 
 
543
    __slots__ = ['raw_path', 'base_path']
 
 
545
    def __init__(self, path, base_path=None):
 
 
546
        """Construct a FastPath from path."""
 
 
547
        if base_path is None:
 
 
548
            self.base_path = osutils.basename(path)
 
 
550
            self.base_path = base_path
 
 
553
    def __cmp__(self, other):
 
 
554
        return cmp(self.raw_path, other.raw_path)
 
 
557
        return hash(self.raw_path)
 
 
560
def _add_one_and_parent(tree, inv, parent_ie, path, kind, action):
 
 
561
    """Add a new entry to the inventory and automatically add unversioned parents.
 
 
563
    :param inv: Inventory which will receive the new entry.
 
 
564
    :param parent_ie: Parent inventory entry if known, or None.  If
 
 
565
        None, the parent is looked up by name and used if present, otherwise it
 
 
566
        is recursively added.
 
 
567
    :param kind: Kind of new entry (file, directory, etc)
 
 
568
    :param action: callback(inv, parent_ie, path, kind); return ignored.
 
 
569
    :return: A list of paths which have been added.
 
 
571
    # Nothing to do if path is already versioned.
 
 
572
    # This is safe from infinite recursion because the tree root is
 
 
574
    if parent_ie is not None:
 
 
575
        # we have a parent ie already
 
 
578
        # slower but does not need parent_ie
 
 
579
        if inv.has_filename(path.raw_path):
 
 
581
        # its really not there : add the parent
 
 
582
        # note that the dirname use leads to some extra str copying etc but as
 
 
583
        # there are a limited number of dirs we can be nested under, it should
 
 
584
        # generally find it very fast and not recurse after that.
 
 
585
        added = _add_one_and_parent(tree, inv, None,
 
 
586
            _FastPath(dirname(path.raw_path)), 'directory', action)
 
 
587
        parent_id = inv.path2id(dirname(path.raw_path))
 
 
588
        parent_ie = inv[parent_id]
 
 
589
    _add_one(tree, inv, parent_ie, path, kind, action)
 
 
590
    return added + [path.raw_path]
 
 
593
def _add_one(tree, inv, parent_ie, path, kind, file_id_callback):
 
 
594
    """Add a new entry to the inventory.
 
 
596
    :param inv: Inventory which will receive the new entry.
 
 
597
    :param parent_ie: Parent inventory entry.
 
 
598
    :param kind: Kind of new entry (file, directory, etc)
 
 
599
    :param file_id_callback: callback(inv, parent_ie, path, kind); return a
 
 
600
        file_id or None to generate a new file id
 
 
603
    file_id = file_id_callback(inv, parent_ie, path, kind)
 
 
604
    entry = inv.make_entry(kind, path.base_path, parent_ie.file_id,