/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/bzr/inventorytree.py

Fix another 40 tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-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
"""Tree classes, representing directory at point in time.
 
18
"""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
import os
 
23
import re
 
24
 
 
25
from .. import (
 
26
    errors,
 
27
    lazy_import,
 
28
    osutils,
 
29
    revision,
 
30
    )
 
31
from ..mutabletree import (
 
32
    MutableTree,
 
33
    )
 
34
from ..revisiontree import (
 
35
    RevisionTree,
 
36
    )
 
37
lazy_import.lazy_import(globals(), """
 
38
from breezy import (
 
39
    add,
 
40
    controldir,
 
41
    trace,
 
42
    transport as _mod_transport,
 
43
    )
 
44
from breezy.bzr import (
 
45
    inventory as _mod_inventory,
 
46
    )
 
47
""")
 
48
from ..sixish import (
 
49
    viewvalues,
 
50
    )
 
51
from ..tree import (
 
52
    FileTimestampUnavailable,
 
53
    InterTree,
 
54
    Tree,
 
55
    )
 
56
 
 
57
 
 
58
class InventoryTree(Tree):
 
59
    """A tree that relies on an inventory for its metadata.
 
60
 
 
61
    Trees contain an `Inventory` object, and also know how to retrieve
 
62
    file texts mentioned in the inventory, either from a working
 
63
    directory or from a store.
 
64
 
 
65
    It is possible for trees to contain files that are not described
 
66
    in their inventory or vice versa; for this use `filenames()`.
 
67
 
 
68
    Subclasses should set the _inventory attribute, which is considered
 
69
    private to external API users.
 
70
    """
 
71
 
 
72
    def get_canonical_inventory_paths(self, paths):
 
73
        """Like get_canonical_inventory_path() but works on multiple items.
 
74
 
 
75
        :param paths: A sequence of paths relative to the root of the tree.
 
76
        :return: A list of paths, with each item the corresponding input path
 
77
        adjusted to account for existing elements that match case
 
78
        insensitively.
 
79
        """
 
80
        with self.lock_read():
 
81
            return list(self._yield_canonical_inventory_paths(paths))
 
82
 
 
83
    def get_canonical_inventory_path(self, path):
 
84
        """Returns the first inventory item that case-insensitively matches path.
 
85
 
 
86
        If a path matches exactly, it is returned. If no path matches exactly
 
87
        but more than one path matches case-insensitively, it is implementation
 
88
        defined which is returned.
 
89
 
 
90
        If no path matches case-insensitively, the input path is returned, but
 
91
        with as many path entries that do exist changed to their canonical
 
92
        form.
 
93
 
 
94
        If you need to resolve many names from the same tree, you should
 
95
        use get_canonical_inventory_paths() to avoid O(N) behaviour.
 
96
 
 
97
        :param path: A paths relative to the root of the tree.
 
98
        :return: The input path adjusted to account for existing elements
 
99
        that match case insensitively.
 
100
        """
 
101
        with self.lock_read():
 
102
            return next(self._yield_canonical_inventory_paths([path]))
 
103
 
 
104
    def _yield_canonical_inventory_paths(self, paths):
 
105
        for path in paths:
 
106
            # First, if the path as specified exists exactly, just use it.
 
107
            if self.path2id(path) is not None:
 
108
                yield path
 
109
                continue
 
110
            # go walkin...
 
111
            cur_id = self.get_root_id()
 
112
            cur_path = ''
 
113
            bit_iter = iter(path.split("/"))
 
114
            for elt in bit_iter:
 
115
                lelt = elt.lower()
 
116
                new_path = None
 
117
                try:
 
118
                    for child in self.iter_child_entries(self.id2path(cur_id), cur_id):
 
119
                        try:
 
120
                            # XXX: it seem like if the child is known to be in the
 
121
                            # tree, we shouldn't need to go from its id back to
 
122
                            # its path -- mbp 2010-02-11
 
123
                            #
 
124
                            # XXX: it seems like we could be more efficient
 
125
                            # by just directly looking up the original name and
 
126
                            # only then searching all children; also by not
 
127
                            # chopping paths so much. -- mbp 2010-02-11
 
128
                            child_base = os.path.basename(self.id2path(child.file_id))
 
129
                            if (child_base == elt):
 
130
                                # if we found an exact match, we can stop now; if
 
131
                                # we found an approximate match we need to keep
 
132
                                # searching because there might be an exact match
 
133
                                # later.  
 
134
                                cur_id = child.file_id
 
135
                                new_path = osutils.pathjoin(cur_path, child_base)
 
136
                                break
 
137
                            elif child_base.lower() == lelt:
 
138
                                cur_id = child.file_id
 
139
                                new_path = osutils.pathjoin(cur_path, child_base)
 
140
                        except errors.NoSuchId:
 
141
                            # before a change is committed we can see this error...
 
142
                            continue
 
143
                except errors.NotADirectory:
 
144
                    pass
 
145
                if new_path:
 
146
                    cur_path = new_path
 
147
                else:
 
148
                    # got to the end of this directory and no entries matched.
 
149
                    # Return what matched so far, plus the rest as specified.
 
150
                    cur_path = osutils.pathjoin(cur_path, elt, *list(bit_iter))
 
151
                    break
 
152
            yield cur_path
 
153
        # all done.
 
154
 
 
155
    def _get_root_inventory(self):
 
156
        return self._inventory
 
157
 
 
158
    root_inventory = property(_get_root_inventory,
 
159
        doc="Root inventory of this tree")
 
160
 
 
161
    def _unpack_file_id(self, file_id):
 
162
        """Find the inventory and inventory file id for a tree file id.
 
163
 
 
164
        :param file_id: The tree file id, as bytestring or tuple
 
165
        :return: Inventory and inventory file id
 
166
        """
 
167
        if isinstance(file_id, tuple):
 
168
            if len(file_id) != 1:
 
169
                raise ValueError("nested trees not yet supported: %r" % file_id)
 
170
            file_id = file_id[0]
 
171
        return self.root_inventory, file_id
 
172
 
 
173
    def find_related_paths_across_trees(self, paths, trees=[],
 
174
            require_versioned=True):
 
175
        """Find related paths in tree corresponding to specified filenames in any
 
176
        of `lookup_trees`.
 
177
 
 
178
        All matches in all trees will be used, and all children of matched
 
179
        directories will be used.
 
180
 
 
181
        :param paths: The filenames to find related paths for (if None, returns
 
182
            None)
 
183
        :param trees: The trees to find file_ids within
 
184
        :param require_versioned: if true, all specified filenames must occur in
 
185
            at least one tree.
 
186
        :return: a set of paths for the specified filenames and their children
 
187
            in `tree`
 
188
        """
 
189
        if paths is None:
 
190
            return None;
 
191
        file_ids = self.paths2ids(
 
192
                paths, trees, require_versioned=require_versioned)
 
193
        ret = set()
 
194
        for file_id in file_ids:
 
195
            try:
 
196
                ret.add(self.id2path(file_id))
 
197
            except errors.NoSuchId:
 
198
                pass
 
199
        return ret
 
200
 
 
201
    def paths2ids(self, paths, trees=[], require_versioned=True):
 
202
        """Return all the ids that can be reached by walking from paths.
 
203
 
 
204
        Each path is looked up in this tree and any extras provided in
 
205
        trees, and this is repeated recursively: the children in an extra tree
 
206
        of a directory that has been renamed under a provided path in this tree
 
207
        are all returned, even if none exist under a provided path in this
 
208
        tree, and vice versa.
 
209
 
 
210
        :param paths: An iterable of paths to start converting to ids from.
 
211
            Alternatively, if paths is None, no ids should be calculated and None
 
212
            will be returned. This is offered to make calling the api unconditional
 
213
            for code that *might* take a list of files.
 
214
        :param trees: Additional trees to consider.
 
215
        :param require_versioned: If False, do not raise NotVersionedError if
 
216
            an element of paths is not versioned in this tree and all of trees.
 
217
        """
 
218
        return find_ids_across_trees(paths, [self] + list(trees), require_versioned)
 
219
 
 
220
    def path2id(self, path):
 
221
        """Return the id for path in this tree."""
 
222
        with self.lock_read():
 
223
            return self._path2inv_file_id(path)[1]
 
224
 
 
225
    def _path2ie(self, path):
 
226
        """Lookup an inventory entry by path.
 
227
 
 
228
        :param path: Path to look up
 
229
        :return: InventoryEntry
 
230
        """
 
231
        ie = self.root_inventory.get_entry_by_path(path)
 
232
        if ie is None:
 
233
            raise errors.NoSuchFile(path)
 
234
        return ie
 
235
 
 
236
    def _path2inv_file_id(self, path):
 
237
        """Lookup a inventory and inventory file id by path.
 
238
 
 
239
        :param path: Path to look up
 
240
        :return: tuple with inventory and inventory file id
 
241
        """
 
242
        # FIXME: Support nested trees
 
243
        inv = self.root_inventory
 
244
        inv_file_id = self.root_inventory.path2id(path)
 
245
        return inv, inv_file_id
 
246
 
 
247
    def id2path(self, file_id):
 
248
        """Return the path for a file id.
 
249
 
 
250
        :raises NoSuchId:
 
251
        """
 
252
        inventory, file_id = self._unpack_file_id(file_id)
 
253
        return inventory.id2path(file_id)
 
254
 
 
255
    def has_id(self, file_id):
 
256
        inventory, file_id = self._unpack_file_id(file_id)
 
257
        return inventory.has_id(file_id)
 
258
 
 
259
    def has_or_had_id(self, file_id):
 
260
        inventory, file_id = self._unpack_file_id(file_id)
 
261
        return inventory.has_id(file_id)
 
262
 
 
263
    def all_file_ids(self):
 
264
        return {entry.file_id for path, entry in self.iter_entries_by_dir()}
 
265
 
 
266
    def all_versioned_paths(self):
 
267
        return {path for path, entry in self.iter_entries_by_dir()}
 
268
 
 
269
    def iter_entries_by_dir(self, specific_files=None):
 
270
        """Walk the tree in 'by_dir' order.
 
271
 
 
272
        This will yield each entry in the tree as a (path, entry) tuple.
 
273
        The order that they are yielded is:
 
274
 
 
275
        See Tree.iter_entries_by_dir for details.
 
276
        """
 
277
        with self.lock_read():
 
278
            if specific_files is not None:
 
279
                inventory_file_ids = []
 
280
                for path in specific_files:
 
281
                    inventory, inv_file_id = self._path2inv_file_id(path)
 
282
                    if not inventory is self.root_inventory: # for now
 
283
                        raise AssertionError("%r != %r" % (
 
284
                            inventory, self.root_inventory))
 
285
                    inventory_file_ids.append(inv_file_id)
 
286
            else:
 
287
                inventory_file_ids = None
 
288
            # FIXME: Handle nested trees
 
289
            return self.root_inventory.iter_entries_by_dir(
 
290
                specific_file_ids=inventory_file_ids)
 
291
 
 
292
    def iter_child_entries(self, path, file_id=None):
 
293
        with self.lock_read():
 
294
            ie = self._path2ie(path)
 
295
            if ie.kind != 'directory':
 
296
                raise errors.NotADirectory(path)
 
297
            return iter(viewvalues(ie.children))
 
298
 
 
299
    def _get_plan_merge_data(self, file_id, other, base):
 
300
        from . import versionedfile
 
301
        vf = versionedfile._PlanMergeVersionedFile(file_id)
 
302
        last_revision_a = self._get_file_revision(
 
303
                self.id2path(file_id), file_id, vf, b'this:')
 
304
        last_revision_b = other._get_file_revision(
 
305
                other.id2path(file_id), file_id, vf, b'other:')
 
306
        if base is None:
 
307
            last_revision_base = None
 
308
        else:
 
309
            last_revision_base = base._get_file_revision(
 
310
                    base.id2path(file_id), file_id, vf, b'base:')
 
311
        return vf, last_revision_a, last_revision_b, last_revision_base
 
312
 
 
313
    def plan_file_merge(self, file_id, other, base=None):
 
314
        """Generate a merge plan based on annotations.
 
315
 
 
316
        If the file contains uncommitted changes in this tree, they will be
 
317
        attributed to the 'current:' pseudo-revision.  If the file contains
 
318
        uncommitted changes in the other tree, they will be assigned to the
 
319
        'other:' pseudo-revision.
 
320
        """
 
321
        data = self._get_plan_merge_data(file_id, other, base)
 
322
        vf, last_revision_a, last_revision_b, last_revision_base = data
 
323
        return vf.plan_merge(last_revision_a, last_revision_b,
 
324
                             last_revision_base)
 
325
 
 
326
    def plan_file_lca_merge(self, file_id, other, base=None):
 
327
        """Generate a merge plan based lca-newness.
 
328
 
 
329
        If the file contains uncommitted changes in this tree, they will be
 
330
        attributed to the 'current:' pseudo-revision.  If the file contains
 
331
        uncommitted changes in the other tree, they will be assigned to the
 
332
        'other:' pseudo-revision.
 
333
        """
 
334
        data = self._get_plan_merge_data(file_id, other, base)
 
335
        vf, last_revision_a, last_revision_b, last_revision_base = data
 
336
        return vf.plan_lca_merge(last_revision_a, last_revision_b,
 
337
                                 last_revision_base)
 
338
 
 
339
    def _get_file_revision(self, path, file_id, vf, tree_revision):
 
340
        """Ensure that file_id, tree_revision is in vf to plan the merge."""
 
341
        if getattr(self, '_repository', None) is None:
 
342
            last_revision = tree_revision
 
343
            parent_keys = [(file_id, t.get_file_revision(path, file_id)) for t in
 
344
                self._iter_parent_trees()]
 
345
            vf.add_lines((file_id, last_revision), parent_keys,
 
346
                         self.get_file_lines(path, file_id))
 
347
            repo = self.branch.repository
 
348
            base_vf = repo.texts
 
349
        else:
 
350
            last_revision = self.get_file_revision(path, file_id)
 
351
            base_vf = self._repository.texts
 
352
        if base_vf not in vf.fallback_versionedfiles:
 
353
            vf.fallback_versionedfiles.append(base_vf)
 
354
        return last_revision
 
355
 
 
356
 
 
357
def find_ids_across_trees(filenames, trees, require_versioned=True):
 
358
    """Find the ids corresponding to specified filenames.
 
359
 
 
360
    All matches in all trees will be used, and all children of matched
 
361
    directories will be used.
 
362
 
 
363
    :param filenames: The filenames to find file_ids for (if None, returns
 
364
        None)
 
365
    :param trees: The trees to find file_ids within
 
366
    :param require_versioned: if true, all specified filenames must occur in
 
367
        at least one tree.
 
368
    :return: a set of file ids for the specified filenames and their children.
 
369
    """
 
370
    if not filenames:
 
371
        return None
 
372
    specified_path_ids = _find_ids_across_trees(filenames, trees,
 
373
        require_versioned)
 
374
    return _find_children_across_trees(specified_path_ids, trees)
 
375
 
 
376
 
 
377
def _find_ids_across_trees(filenames, trees, require_versioned):
 
378
    """Find the ids corresponding to specified filenames.
 
379
 
 
380
    All matches in all trees will be used, but subdirectories are not scanned.
 
381
 
 
382
    :param filenames: The filenames to find file_ids for
 
383
    :param trees: The trees to find file_ids within
 
384
    :param require_versioned: if true, all specified filenames must occur in
 
385
        at least one tree.
 
386
    :return: a set of file ids for the specified filenames
 
387
    """
 
388
    not_versioned = []
 
389
    interesting_ids = set()
 
390
    for tree_path in filenames:
 
391
        not_found = True
 
392
        for tree in trees:
 
393
            file_id = tree.path2id(tree_path)
 
394
            if file_id is not None:
 
395
                interesting_ids.add(file_id)
 
396
                not_found = False
 
397
        if not_found:
 
398
            not_versioned.append(tree_path)
 
399
    if len(not_versioned) > 0 and require_versioned:
 
400
        raise errors.PathsNotVersionedError(not_versioned)
 
401
    return interesting_ids
 
402
 
 
403
 
 
404
def _find_children_across_trees(specified_ids, trees):
 
405
    """Return a set including specified ids and their children.
 
406
 
 
407
    All matches in all trees will be used.
 
408
 
 
409
    :param trees: The trees to find file_ids within
 
410
    :return: a set containing all specified ids and their children
 
411
    """
 
412
    interesting_ids = set(specified_ids)
 
413
    pending = interesting_ids
 
414
    # now handle children of interesting ids
 
415
    # we loop so that we handle all children of each id in both trees
 
416
    while len(pending) > 0:
 
417
        new_pending = set()
 
418
        for file_id in pending:
 
419
            for tree in trees:
 
420
                try:
 
421
                    path = tree.id2path(file_id)
 
422
                except errors.NoSuchId:
 
423
                    continue
 
424
                try:
 
425
                    for child in tree.iter_child_entries(path, file_id):
 
426
                        if child.file_id not in interesting_ids:
 
427
                            new_pending.add(child.file_id)
 
428
                except errors.NotADirectory:
 
429
                    pass
 
430
        interesting_ids.update(new_pending)
 
431
        pending = new_pending
 
432
    return interesting_ids
 
433
 
 
434
 
 
435
class MutableInventoryTree(MutableTree, InventoryTree):
 
436
 
 
437
    def apply_inventory_delta(self, changes):
 
438
        """Apply changes to the inventory as an atomic operation.
 
439
 
 
440
        :param changes: An inventory delta to apply to the working tree's
 
441
            inventory.
 
442
        :return None:
 
443
        :seealso Inventory.apply_delta: For details on the changes parameter.
 
444
        """
 
445
        with self.lock_tree_write():
 
446
            self.flush()
 
447
            inv = self.root_inventory
 
448
            inv.apply_delta(changes)
 
449
            self._write_inventory(inv)
 
450
 
 
451
    def _fix_case_of_inventory_path(self, path):
 
452
        """If our tree isn't case sensitive, return the canonical path"""
 
453
        if not self.case_sensitive:
 
454
            path = self.get_canonical_inventory_path(path)
 
455
        return path
 
456
 
 
457
    def smart_add(self, file_list, recurse=True, action=None, save=True):
 
458
        """Version file_list, optionally recursing into directories.
 
459
 
 
460
        This is designed more towards DWIM for humans than API clarity.
 
461
        For the specific behaviour see the help for cmd_add().
 
462
 
 
463
        :param file_list: List of zero or more paths.  *NB: these are
 
464
            interpreted relative to the process cwd, not relative to the
 
465
            tree.*  (Add and most other tree methods use tree-relative
 
466
            paths.)
 
467
        :param action: A reporter to be called with the inventory, parent_ie,
 
468
            path and kind of the path being added. It may return a file_id if
 
469
            a specific one should be used.
 
470
        :param save: Save the inventory after completing the adds. If False
 
471
            this provides dry-run functionality by doing the add and not saving
 
472
            the inventory.
 
473
        :return: A tuple - files_added, ignored_files. files_added is the count
 
474
            of added files, and ignored_files is a dict mapping files that were
 
475
            ignored to the rule that caused them to be ignored.
 
476
        """
 
477
        with self.lock_tree_write():
 
478
            # Not all mutable trees can have conflicts
 
479
            if getattr(self, 'conflicts', None) is not None:
 
480
                # Collect all related files without checking whether they exist or
 
481
                # are versioned. It's cheaper to do that once for all conflicts
 
482
                # than trying to find the relevant conflict for each added file.
 
483
                conflicts_related = set()
 
484
                for c in self.conflicts():
 
485
                    conflicts_related.update(c.associated_filenames())
 
486
            else:
 
487
                conflicts_related = None
 
488
            adder = _SmartAddHelper(self, action, conflicts_related)
 
489
            adder.add(file_list, recurse=recurse)
 
490
            if save:
 
491
                invdelta = adder.get_inventory_delta()
 
492
                self.apply_inventory_delta(invdelta)
 
493
            return adder.added, adder.ignored
 
494
 
 
495
    def update_basis_by_delta(self, new_revid, delta):
 
496
        """Update the parents of this tree after a commit.
 
497
 
 
498
        This gives the tree one parent, with revision id new_revid. The
 
499
        inventory delta is applied to the current basis tree to generate the
 
500
        inventory for the parent new_revid, and all other parent trees are
 
501
        discarded.
 
502
 
 
503
        All the changes in the delta should be changes synchronising the basis
 
504
        tree with some or all of the working tree, with a change to a directory
 
505
        requiring that its contents have been recursively included. That is,
 
506
        this is not a general purpose tree modification routine, but a helper
 
507
        for commit which is not required to handle situations that do not arise
 
508
        outside of commit.
 
509
 
 
510
        See the inventory developers documentation for the theory behind
 
511
        inventory deltas.
 
512
 
 
513
        :param new_revid: The new revision id for the trees parent.
 
514
        :param delta: An inventory delta (see apply_inventory_delta) describing
 
515
            the changes from the current left most parent revision to new_revid.
 
516
        """
 
517
        # if the tree is updated by a pull to the branch, as happens in
 
518
        # WorkingTree2, when there was no separation between branch and tree,
 
519
        # then just clear merges, efficiency is not a concern for now as this
 
520
        # is legacy environments only, and they are slow regardless.
 
521
        if self.last_revision() == new_revid:
 
522
            self.set_parent_ids([new_revid])
 
523
            return
 
524
        # generic implementation based on Inventory manipulation. See
 
525
        # WorkingTree classes for optimised versions for specific format trees.
 
526
        basis = self.basis_tree()
 
527
        with basis.lock_read():
 
528
            # TODO: Consider re-evaluating the need for this with CHKInventory
 
529
            # we don't strictly need to mutate an inventory for this
 
530
            # it only makes sense when apply_delta is cheaper than get_inventory()
 
531
            inventory = _mod_inventory.mutable_inventory_from_tree(basis)
 
532
        inventory.apply_delta(delta)
 
533
        rev_tree = InventoryRevisionTree(self.branch.repository,
 
534
                                         inventory, new_revid)
 
535
        self.set_parent_trees([(new_revid, rev_tree)])
 
536
 
 
537
 
 
538
class _SmartAddHelper(object):
 
539
    """Helper for MutableTree.smart_add."""
 
540
 
 
541
    def get_inventory_delta(self):
 
542
        # GZ 2016-06-05: Returning view would probably be fine but currently
 
543
        # Inventory.apply_delta is documented as requiring a list of changes.
 
544
        return list(viewvalues(self._invdelta))
 
545
 
 
546
    def _get_ie(self, inv_path):
 
547
        """Retrieve the most up to date inventory entry for a path.
 
548
 
 
549
        :param inv_path: Normalized inventory path
 
550
        :return: Inventory entry (with possibly invalid .children for
 
551
            directories)
 
552
        """
 
553
        entry = self._invdelta.get(inv_path)
 
554
        if entry is not None:
 
555
            return entry[3]
 
556
        # Find a 'best fit' match if the filesystem is case-insensitive
 
557
        inv_path = self.tree._fix_case_of_inventory_path(inv_path)
 
558
        try:
 
559
            return next(self.tree.iter_entries_by_dir(
 
560
                    specific_files=[inv_path]))[1]
 
561
        except StopIteration:
 
562
            return None
 
563
 
 
564
    def _convert_to_directory(self, this_ie, inv_path):
 
565
        """Convert an entry to a directory.
 
566
 
 
567
        :param this_ie: Inventory entry
 
568
        :param inv_path: Normalized path for the inventory entry
 
569
        :return: The new inventory entry
 
570
        """
 
571
        # Same as in _add_one below, if the inventory doesn't
 
572
        # think this is a directory, update the inventory
 
573
        this_ie = _mod_inventory.InventoryDirectory(
 
574
            this_ie.file_id, this_ie.name, this_ie.parent_id)
 
575
        self._invdelta[inv_path] = (inv_path, inv_path, this_ie.file_id,
 
576
            this_ie)
 
577
        return this_ie
 
578
 
 
579
    def _add_one_and_parent(self, parent_ie, path, kind, inv_path):
 
580
        """Add a new entry to the inventory and automatically add unversioned parents.
 
581
 
 
582
        :param parent_ie: Parent inventory entry if known, or None.  If
 
583
            None, the parent is looked up by name and used if present, otherwise it
 
584
            is recursively added.
 
585
        :param path: Filesystem path to add
 
586
        :param kind: Kind of new entry (file, directory, etc)
 
587
        :param inv_path: Inventory path
 
588
        :return: Inventory entry for path and a list of paths which have been added.
 
589
        """
 
590
        # Nothing to do if path is already versioned.
 
591
        # This is safe from infinite recursion because the tree root is
 
592
        # always versioned.
 
593
        inv_dirname = osutils.dirname(inv_path)
 
594
        dirname, basename = osutils.split(path)
 
595
        if parent_ie is None:
 
596
            # slower but does not need parent_ie
 
597
            this_ie = self._get_ie(inv_path)
 
598
            if this_ie is not None:
 
599
                return this_ie
 
600
            # its really not there : add the parent
 
601
            # note that the dirname use leads to some extra str copying etc but as
 
602
            # there are a limited number of dirs we can be nested under, it should
 
603
            # generally find it very fast and not recurse after that.
 
604
            parent_ie = self._add_one_and_parent(None,
 
605
                dirname, 'directory', 
 
606
                inv_dirname)
 
607
        # if the parent exists, but isn't a directory, we have to do the
 
608
        # kind change now -- really the inventory shouldn't pretend to know
 
609
        # the kind of wt files, but it does.
 
610
        if parent_ie.kind != 'directory':
 
611
            # nb: this relies on someone else checking that the path we're using
 
612
            # doesn't contain symlinks.
 
613
            parent_ie = self._convert_to_directory(parent_ie, inv_dirname)
 
614
        file_id = self.action(self.tree, parent_ie, path, kind)
 
615
        entry = _mod_inventory.make_entry(kind, basename, parent_ie.file_id,
 
616
            file_id=file_id)
 
617
        self._invdelta[inv_path] = (None, inv_path, entry.file_id, entry)
 
618
        self.added.append(inv_path)
 
619
        return entry
 
620
 
 
621
    def _gather_dirs_to_add(self, user_dirs):
 
622
        # only walk the minimal parents needed: we have user_dirs to override
 
623
        # ignores.
 
624
        prev_dir = None
 
625
 
 
626
        is_inside = osutils.is_inside_or_parent_of_any
 
627
        for path in sorted(user_dirs):
 
628
            if (prev_dir is None or not is_inside([prev_dir], path)):
 
629
                inv_path, this_ie = user_dirs[path]
 
630
                yield (path, inv_path, this_ie, None)
 
631
            prev_dir = path
 
632
 
 
633
    def __init__(self, tree, action, conflicts_related=None):
 
634
        self.tree = tree
 
635
        if action is None:
 
636
            self.action = add.AddAction()
 
637
        else:
 
638
            self.action = action
 
639
        self._invdelta = {}
 
640
        self.added = []
 
641
        self.ignored = {}
 
642
        if conflicts_related is None:
 
643
            self.conflicts_related = frozenset()
 
644
        else:
 
645
            self.conflicts_related = conflicts_related
 
646
 
 
647
    def add(self, file_list, recurse=True):
 
648
        if not file_list:
 
649
            # no paths supplied: add the entire tree.
 
650
            # FIXME: this assumes we are running in a working tree subdir :-/
 
651
            # -- vila 20100208
 
652
            file_list = [u'.']
 
653
 
 
654
        # expand any symlinks in the directory part, while leaving the
 
655
        # filename alone
 
656
        # only expanding if symlinks are supported avoids windows path bugs
 
657
        if osutils.has_symlinks():
 
658
            file_list = list(map(osutils.normalizepath, file_list))
 
659
 
 
660
        user_dirs = {}
 
661
        # validate user file paths and convert all paths to tree
 
662
        # relative : it's cheaper to make a tree relative path an abspath
 
663
        # than to convert an abspath to tree relative, and it's cheaper to
 
664
        # perform the canonicalization in bulk.
 
665
        for filepath in osutils.canonical_relpaths(self.tree.basedir, file_list):
 
666
            # validate user parameters. Our recursive code avoids adding new
 
667
            # files that need such validation
 
668
            if self.tree.is_control_filename(filepath):
 
669
                raise errors.ForbiddenControlFileError(filename=filepath)
 
670
 
 
671
            abspath = self.tree.abspath(filepath)
 
672
            kind = osutils.file_kind(abspath)
 
673
            # ensure the named path is added, so that ignore rules in the later
 
674
            # directory walk dont skip it.
 
675
            # we dont have a parent ie known yet.: use the relatively slower
 
676
            # inventory probing method
 
677
            inv_path, _ = osutils.normalized_filename(filepath)
 
678
            this_ie = self._get_ie(inv_path)
 
679
            if this_ie is None:
 
680
                this_ie = self._add_one_and_parent(None, filepath, kind, inv_path)
 
681
            if kind == 'directory':
 
682
                # schedule the dir for scanning
 
683
                user_dirs[filepath] = (inv_path, this_ie)
 
684
 
 
685
        if not recurse:
 
686
            # no need to walk any directories at all.
 
687
            return
 
688
 
 
689
        things_to_add = list(self._gather_dirs_to_add(user_dirs))
 
690
 
 
691
        illegalpath_re = re.compile(r'[\r\n]')
 
692
        for directory, inv_path, this_ie, parent_ie in things_to_add:
 
693
            # directory is tree-relative
 
694
            abspath = self.tree.abspath(directory)
 
695
 
 
696
            # get the contents of this directory.
 
697
 
 
698
            # find the kind of the path being added, and save stat_value
 
699
            # for reuse
 
700
            stat_value = None
 
701
            if this_ie is None:
 
702
                stat_value = osutils.file_stat(abspath)
 
703
                kind = osutils.file_kind_from_stat_mode(stat_value.st_mode)
 
704
            else:
 
705
                kind = this_ie.kind
 
706
 
 
707
            # allow AddAction to skip this file
 
708
            if self.action.skip_file(self.tree,  abspath,  kind,  stat_value):
 
709
                continue
 
710
            if not _mod_inventory.InventoryEntry.versionable_kind(kind):
 
711
                trace.warning("skipping %s (can't add file of kind '%s')",
 
712
                              abspath, kind)
 
713
                continue
 
714
            if illegalpath_re.search(directory):
 
715
                trace.warning("skipping %r (contains \\n or \\r)" % abspath)
 
716
                continue
 
717
            if directory in self.conflicts_related:
 
718
                # If the file looks like one generated for a conflict, don't
 
719
                # add it.
 
720
                trace.warning(
 
721
                    'skipping %s (generated to help resolve conflicts)',
 
722
                    abspath)
 
723
                continue
 
724
 
 
725
            if kind == 'directory' and directory != '':
 
726
                try:
 
727
                    transport = _mod_transport.get_transport_from_path(abspath)
 
728
                    controldir.ControlDirFormat.find_format(transport)
 
729
                    sub_tree = True
 
730
                except errors.NotBranchError:
 
731
                    sub_tree = False
 
732
                except errors.UnsupportedFormatError:
 
733
                    sub_tree = True
 
734
            else:
 
735
                sub_tree = False
 
736
 
 
737
            if this_ie is not None:
 
738
                pass
 
739
            elif sub_tree:
 
740
                # XXX: This is wrong; people *might* reasonably be trying to
 
741
                # add subtrees as subtrees.  This should probably only be done
 
742
                # in formats which can represent subtrees, and even then
 
743
                # perhaps only when the user asked to add subtrees.  At the
 
744
                # moment you can add them specially through 'join --reference',
 
745
                # which is perhaps reasonable: adding a new reference is a
 
746
                # special operation and can have a special behaviour.  mbp
 
747
                # 20070306
 
748
                trace.warning("skipping nested tree %r", abspath)
 
749
            else:
 
750
                this_ie = self._add_one_and_parent(parent_ie, directory, kind,
 
751
                    inv_path)
 
752
 
 
753
            if kind == 'directory' and not sub_tree:
 
754
                if this_ie.kind != 'directory':
 
755
                    this_ie = self._convert_to_directory(this_ie, inv_path)
 
756
 
 
757
                for subf in sorted(os.listdir(abspath)):
 
758
                    inv_f, _ = osutils.normalized_filename(subf)
 
759
                    # here we could use TreeDirectory rather than
 
760
                    # string concatenation.
 
761
                    subp = osutils.pathjoin(directory, subf)
 
762
                    # TODO: is_control_filename is very slow. Make it faster.
 
763
                    # TreeDirectory.is_control_filename could also make this
 
764
                    # faster - its impossible for a non root dir to have a
 
765
                    # control file.
 
766
                    if self.tree.is_control_filename(subp):
 
767
                        trace.mutter("skip control directory %r", subp)
 
768
                        continue
 
769
                    sub_invp = osutils.pathjoin(inv_path, inv_f)
 
770
                    entry = self._invdelta.get(sub_invp)
 
771
                    if entry is not None:
 
772
                        sub_ie = entry[3]
 
773
                    else:
 
774
                        sub_ie = this_ie.children.get(inv_f)
 
775
                    if sub_ie is not None:
 
776
                        # recurse into this already versioned subdir.
 
777
                        things_to_add.append((subp, sub_invp, sub_ie, this_ie))
 
778
                    else:
 
779
                        # user selection overrides ignores
 
780
                        # ignore while selecting files - if we globbed in the
 
781
                        # outer loop we would ignore user files.
 
782
                        ignore_glob = self.tree.is_ignored(subp)
 
783
                        if ignore_glob is not None:
 
784
                            self.ignored.setdefault(ignore_glob, []).append(subp)
 
785
                        else:
 
786
                            things_to_add.append((subp, sub_invp, None, this_ie))
 
787
 
 
788
 
 
789
class InventoryRevisionTree(RevisionTree, InventoryTree):
 
790
 
 
791
    def __init__(self, repository, inv, revision_id):
 
792
        RevisionTree.__init__(self, repository, revision_id)
 
793
        self._inventory = inv
 
794
 
 
795
    def get_file_mtime(self, path, file_id=None):
 
796
        ie = self._path2ie(path)
 
797
        try:
 
798
            revision = self._repository.get_revision(ie.revision)
 
799
        except errors.NoSuchRevision:
 
800
            raise FileTimestampUnavailable(self.id2path(file_id))
 
801
        return revision.timestamp
 
802
 
 
803
    def get_file_size(self, path, file_id=None):
 
804
        return self._path2ie(path).text_size
 
805
 
 
806
    def get_file_sha1(self, path, file_id=None, stat_value=None):
 
807
        ie = self._path2ie(path)
 
808
        if ie.kind == "file":
 
809
            return ie.text_sha1
 
810
        return None
 
811
 
 
812
    def get_file_revision(self, path, file_id=None):
 
813
        return self._path2ie(path).revision
 
814
 
 
815
    def is_executable(self, path, file_id=None):
 
816
        ie = self._path2ie(path)
 
817
        if ie.kind != "file":
 
818
            return False
 
819
        return ie.executable
 
820
 
 
821
    def has_filename(self, filename):
 
822
        return bool(self.path2id(filename))
 
823
 
 
824
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
825
        # The only files returned by this are those from the version
 
826
        if from_dir is None:
 
827
            from_dir_id = None
 
828
            inv = self.root_inventory
 
829
        else:
 
830
            inv, from_dir_id = self._path2inv_file_id(from_dir)
 
831
            if from_dir_id is None:
 
832
                # Directory not versioned
 
833
                return
 
834
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
 
835
        if inv.root is not None and not include_root and from_dir is None:
 
836
            # skip the root for compatability with the current apis.
 
837
            next(entries)
 
838
        for path, entry in entries:
 
839
            yield path, 'V', entry.kind, entry.file_id, entry
 
840
 
 
841
    def get_symlink_target(self, path, file_id=None):
 
842
        # Inventories store symlink targets in unicode
 
843
        return self._path2ie(path).symlink_target
 
844
 
 
845
    def get_reference_revision(self, path, file_id=None):
 
846
        return self._path2ie(path).reference_revision
 
847
 
 
848
    def get_root_id(self):
 
849
        if self.root_inventory.root:
 
850
            return self.root_inventory.root.file_id
 
851
 
 
852
    def kind(self, path, file_id=None):
 
853
        return self._path2ie(path).kind
 
854
 
 
855
    def path_content_summary(self, path):
 
856
        """See Tree.path_content_summary."""
 
857
        try:
 
858
            entry = self._path2ie(path)
 
859
        except errors.NoSuchFile:
 
860
            return ('missing', None, None, None)
 
861
        kind = entry.kind
 
862
        if kind == 'file':
 
863
            return (kind, entry.text_size, entry.executable, entry.text_sha1)
 
864
        elif kind == 'symlink':
 
865
            return (kind, None, None, entry.symlink_target)
 
866
        else:
 
867
            return (kind, None, None, None)
 
868
 
 
869
    def _comparison_data(self, entry, path):
 
870
        if entry is None:
 
871
            return None, False, None
 
872
        return entry.kind, entry.executable, None
 
873
 
 
874
    def walkdirs(self, prefix=""):
 
875
        _directory = 'directory'
 
876
        inv, top_id = self._path2inv_file_id(prefix)
 
877
        if top_id is None:
 
878
            pending = []
 
879
        else:
 
880
            pending = [(prefix, '', _directory, None, top_id, None)]
 
881
        while pending:
 
882
            dirblock = []
 
883
            currentdir = pending.pop()
 
884
            # 0 - relpath, 1- basename, 2- kind, 3- stat, id, v-kind
 
885
            if currentdir[0]:
 
886
                relroot = currentdir[0] + '/'
 
887
            else:
 
888
                relroot = ""
 
889
            # FIXME: stash the node in pending
 
890
            entry = inv.get_entry(currentdir[4])
 
891
            for name, child in entry.sorted_children():
 
892
                toppath = relroot + name
 
893
                dirblock.append((toppath, name, child.kind, None,
 
894
                    child.file_id, child.kind
 
895
                    ))
 
896
            yield (currentdir[0], entry.file_id), dirblock
 
897
            # push the user specified dirs from dirblock
 
898
            for dir in reversed(dirblock):
 
899
                if dir[2] == _directory:
 
900
                    pending.append(dir)
 
901
 
 
902
    def iter_files_bytes(self, desired_files):
 
903
        """See Tree.iter_files_bytes.
 
904
 
 
905
        This version is implemented on top of Repository.iter_files_bytes"""
 
906
        repo_desired_files = [(self.path2id(f), self.get_file_revision(f), i)
 
907
                              for f, i in desired_files]
 
908
        try:
 
909
            for result in self._repository.iter_files_bytes(repo_desired_files):
 
910
                yield result
 
911
        except errors.RevisionNotPresent as e:
 
912
            raise errors.NoSuchFile(e.file_id)
 
913
 
 
914
    def annotate_iter(self, path, file_id=None,
 
915
                      default_revision=revision.CURRENT_REVISION):
 
916
        """See Tree.annotate_iter"""
 
917
        if file_id is None:
 
918
            file_id = self.path2id(path)
 
919
        text_key = (file_id, self.get_file_revision(path, file_id))
 
920
        annotator = self._repository.texts.get_annotator()
 
921
        annotations = annotator.annotate_flat(text_key)
 
922
        return [(key[-1], line) for key, line in annotations]
 
923
 
 
924
    def __eq__(self, other):
 
925
        if self is other:
 
926
            return True
 
927
        if isinstance(other, InventoryRevisionTree):
 
928
            return (self.root_inventory == other.root_inventory)
 
929
        return False
 
930
 
 
931
    def __ne__(self, other):
 
932
        return not (self == other)
 
933
 
 
934
    def __hash__(self):
 
935
        raise ValueError('not hashable')
 
936
 
 
937
 
 
938
class InterCHKRevisionTree(InterTree):
 
939
    """Fast path optimiser for RevisionTrees with CHK inventories."""
 
940
 
 
941
    @staticmethod
 
942
    def is_compatible(source, target):
 
943
        if (isinstance(source, RevisionTree)
 
944
            and isinstance(target, RevisionTree)):
 
945
            try:
 
946
                # Only CHK inventories have id_to_entry attribute
 
947
                source.root_inventory.id_to_entry
 
948
                target.root_inventory.id_to_entry
 
949
                return True
 
950
            except AttributeError:
 
951
                pass
 
952
        return False
 
953
 
 
954
    def iter_changes(self, include_unchanged=False,
 
955
                     specific_files=None, pb=None, extra_trees=[],
 
956
                     require_versioned=True, want_unversioned=False):
 
957
        lookup_trees = [self.source]
 
958
        if extra_trees:
 
959
             lookup_trees.extend(extra_trees)
 
960
        # The ids of items we need to examine to insure delta consistency.
 
961
        precise_file_ids = set()
 
962
        discarded_changes = {}
 
963
        if specific_files == []:
 
964
            specific_file_ids = []
 
965
        else:
 
966
            specific_file_ids = self.target.paths2ids(specific_files,
 
967
                lookup_trees, require_versioned=require_versioned)
 
968
        # FIXME: It should be possible to delegate include_unchanged handling
 
969
        # to CHKInventory.iter_changes and do a better job there -- vila
 
970
        # 20090304
 
971
        changed_file_ids = set()
 
972
        # FIXME: nested tree support
 
973
        for result in self.target.root_inventory.iter_changes(
 
974
                self.source.root_inventory):
 
975
            if specific_file_ids is not None:
 
976
                file_id = result[0]
 
977
                if file_id not in specific_file_ids:
 
978
                    # A change from the whole tree that we don't want to show yet.
 
979
                    # We may find that we need to show it for delta consistency, so
 
980
                    # stash it.
 
981
                    discarded_changes[result[0]] = result
 
982
                    continue
 
983
                new_parent_id = result[4][1]
 
984
                precise_file_ids.add(new_parent_id)
 
985
            yield result
 
986
            changed_file_ids.add(result[0])
 
987
        if specific_file_ids is not None:
 
988
            for result in self._handle_precise_ids(precise_file_ids,
 
989
                changed_file_ids, discarded_changes=discarded_changes):
 
990
                yield result
 
991
        if include_unchanged:
 
992
            # CHKMap avoid being O(tree), so we go to O(tree) only if
 
993
            # required to.
 
994
            # Now walk the whole inventory, excluding the already yielded
 
995
            # file ids
 
996
            # FIXME: Support nested trees
 
997
            changed_file_ids = set(changed_file_ids)
 
998
            for relpath, entry in self.target.root_inventory.iter_entries():
 
999
                if (specific_file_ids is not None
 
1000
                    and not entry.file_id in specific_file_ids):
 
1001
                    continue
 
1002
                if not entry.file_id in changed_file_ids:
 
1003
                    yield (entry.file_id,
 
1004
                           (relpath, relpath), # Not renamed
 
1005
                           False, # Not modified
 
1006
                           (True, True), # Still  versioned
 
1007
                           (entry.parent_id, entry.parent_id),
 
1008
                           (entry.name, entry.name),
 
1009
                           (entry.kind, entry.kind),
 
1010
                           (entry.executable, entry.executable))
 
1011
 
 
1012
 
 
1013
InterTree.register_optimiser(InterCHKRevisionTree)