~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: Vincent Ladeuil
  • Date: 2009-05-04 14:48:21 UTC
  • mto: (4349.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4350.
  • Revision ID: v.ladeuil+lp@free.fr-20090504144821-39dvqkikmd3zqkdg
Handle servers proposing several authentication schemes.

* bzrlib/transport/http/_urllib2_wrappers.py:
(AbstractAuthHandler.auth_required): Several schemes can be
proposed by the server, try to match each one in turn.
(BasicAuthHandler.auth_match): Delete dead code.

* bzrlib/tests/test_http.py:
(load_tests): Separate proxy and http authentication tests as they
require different server setups.
(TestAuth.create_transport_readonly_server): Simplified by using
parameter provided by load_tests.
(TestAuth.test_changing_nonce): Adapt to new parametrization.
(TestProxyAuth.create_transport_readonly_server): Deleted.

* bzrlib/tests/http_utils.py:
(DigestAndBasicAuthRequestHandler, HTTPBasicAndDigestAuthServer,
ProxyBasicAndDigestAuthServer): Add a test server proposing both
basic and digest auth schemes but accepting only digest as valid.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2009 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
18
18
"""
19
19
 
20
20
import os
21
 
 
22
 
from bzrlib.lazy_import import lazy_import
23
 
lazy_import(globals(), """
24
 
import collections
25
 
 
 
21
from collections import deque
 
22
from cStringIO import StringIO
 
23
 
 
24
import bzrlib
26
25
from bzrlib import (
27
26
    conflicts as _mod_conflicts,
28
27
    debug,
29
28
    delta,
30
 
    errors,
31
29
    filters,
32
 
    inventory,
33
30
    osutils,
34
31
    revision as _mod_revision,
35
32
    rules,
36
 
    trace,
 
33
    symbol_versioning,
37
34
    )
38
 
""")
39
 
 
40
35
from bzrlib.decorators import needs_read_lock
 
36
from bzrlib.errors import BzrError, BzrCheckError, NoSuchId
 
37
from bzrlib import errors
 
38
from bzrlib.inventory import Inventory, InventoryFile
41
39
from bzrlib.inter import InterObject
42
 
from bzrlib.symbol_versioning import (
43
 
    deprecated_in,
44
 
    deprecated_method,
45
 
    )
 
40
from bzrlib.osutils import fingerprint_file
 
41
import bzrlib.revision
 
42
from bzrlib.symbol_versioning import deprecated_function, deprecated_in
 
43
from bzrlib.trace import mutter, note
46
44
 
47
45
 
48
46
class Tree(object):
54
52
 
55
53
    * `RevisionTree` is a tree as recorded at some point in the past.
56
54
 
 
55
    Trees contain an `Inventory` object, and also know how to retrieve
 
56
    file texts mentioned in the inventory, either from a working
 
57
    directory or from a store.
 
58
 
 
59
    It is possible for trees to contain files that are not described
 
60
    in their inventory or vice versa; for this use `filenames()`.
 
61
 
57
62
    Trees can be compared, etc, regardless of whether they are working
58
63
    trees or versioned trees.
59
64
    """
95
100
    def iter_changes(self, from_tree, include_unchanged=False,
96
101
                     specific_files=None, pb=None, extra_trees=None,
97
102
                     require_versioned=True, want_unversioned=False):
98
 
        """See InterTree.iter_changes"""
99
103
        intertree = InterTree.get(from_tree, self)
100
104
        return intertree.iter_changes(include_unchanged, specific_files, pb,
101
105
            extra_trees, require_versioned, want_unversioned=want_unversioned)
125
129
        raise NotImplementedError(self.has_filename)
126
130
 
127
131
    def has_id(self, file_id):
128
 
        raise NotImplementedError(self.has_id)
 
132
        return self.inventory.has_id(file_id)
129
133
 
130
 
    @deprecated_method(deprecated_in((2, 4, 0)))
131
134
    def __contains__(self, file_id):
132
135
        return self.has_id(file_id)
133
136
 
134
137
    def has_or_had_id(self, file_id):
135
 
        raise NotImplementedError(self.has_or_had_id)
 
138
        if file_id == self.inventory.root.file_id:
 
139
            return True
 
140
        return self.inventory.has_id(file_id)
136
141
 
137
142
    def is_ignored(self, filename):
138
143
        """Check whether the filename is ignored by this tree.
142
147
        """
143
148
        return False
144
149
 
 
150
    def __iter__(self):
 
151
        return iter(self.inventory)
 
152
 
145
153
    def all_file_ids(self):
146
154
        """Iterate through all file ids, including ids for missing files."""
147
 
        raise NotImplementedError(self.all_file_ids)
 
155
        return set(self.inventory)
148
156
 
149
157
    def id2path(self, file_id):
150
158
        """Return the path for a file id.
151
159
 
152
160
        :raises NoSuchId:
153
161
        """
154
 
        raise NotImplementedError(self.id2path)
155
 
 
156
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
162
        return self.inventory.id2path(file_id)
 
163
 
 
164
    def is_control_filename(self, filename):
 
165
        """True if filename is the name of a control file in this tree.
 
166
 
 
167
        :param filename: A filename within the tree. This is a relative path
 
168
        from the root of this tree.
 
169
 
 
170
        This is true IF and ONLY IF the filename is part of the meta data
 
171
        that bzr controls in this tree. I.E. a random .bzr directory placed
 
172
        on disk will not be a control file for this tree.
 
173
        """
 
174
        return self.bzrdir.is_control_filename(filename)
 
175
 
 
176
    @needs_read_lock
 
177
    def iter_entries_by_dir(self, specific_file_ids=None):
157
178
        """Walk the tree in 'by_dir' order.
158
179
 
159
180
        This will yield each entry in the tree as a (path, entry) tuple.
175
196
             g
176
197
 
177
198
        The yield order (ignoring root) would be::
178
 
 
179
199
          a, f, a/b, a/d, a/b/c, a/d/e, f/g
180
 
 
181
 
        :param yield_parents: If True, yield the parents from the root leading
182
 
            down to specific_file_ids that have been requested. This has no
183
 
            impact if specific_file_ids is None.
184
 
        """
185
 
        raise NotImplementedError(self.iter_entries_by_dir)
186
 
 
187
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
188
 
        """List all files in this tree.
189
 
 
190
 
        :param include_root: Whether to include the entry for the tree root
191
 
        :param from_dir: Directory under which to list files
192
 
        :param recursive: Whether to list files recursively
193
 
        :return: iterator over tuples of (path, versioned, kind, file_id,
194
 
            inventory entry)
195
 
        """
196
 
        raise NotImplementedError(self.list_files)
 
200
        """
 
201
        return self.inventory.iter_entries_by_dir(
 
202
            specific_file_ids=specific_file_ids)
197
203
 
198
204
    def iter_references(self):
199
 
        if self.supports_tree_reference():
200
 
            for path, entry in self.iter_entries_by_dir():
201
 
                if entry.kind == 'tree-reference':
202
 
                    yield path, entry.file_id
 
205
        for path, entry in self.iter_entries_by_dir():
 
206
            if entry.kind == 'tree-reference':
 
207
                yield path, entry.file_id
203
208
 
204
209
    def kind(self, file_id):
205
210
        raise NotImplementedError("Tree subclass %s must implement kind"
216
221
    def path_content_summary(self, path):
217
222
        """Get a summary of the information about path.
218
223
 
219
 
        All the attributes returned are for the canonical form, not the
220
 
        convenient form (if content filters are in use.)
221
 
 
222
224
        :param path: A relative path within the tree.
223
225
        :return: A tuple containing kind, size, exec, sha1-or-link.
224
226
            Kind is always present (see tree.kind()).
225
 
            size is present if kind is file and the size of the 
226
 
                canonical form can be cheaply determined, None otherwise.
 
227
            size is present if kind is file, None otherwise.
227
228
            exec is None unless kind is file and the platform supports the 'x'
228
229
                bit.
229
230
            sha1-or-link is the link target if kind is symlink, or the sha1 if
250
251
    def _file_size(self, entry, stat_value):
251
252
        raise NotImplementedError(self._file_size)
252
253
 
 
254
    def _get_inventory(self):
 
255
        return self._inventory
 
256
 
253
257
    def get_file(self, file_id, path=None):
254
258
        """Return a file object for the file file_id in the tree.
255
259
 
258
262
        """
259
263
        raise NotImplementedError(self.get_file)
260
264
 
261
 
    def get_file_with_stat(self, file_id, path=None):
262
 
        """Get a file handle and stat object for file_id.
263
 
 
264
 
        The default implementation returns (self.get_file, None) for backwards
265
 
        compatibility.
266
 
 
267
 
        :param file_id: The file id to read.
268
 
        :param path: The path of the file, if it is known.
269
 
        :return: A tuple (file_handle, stat_value_or_None). If the tree has
270
 
            no stat facility, or need for a stat cache feedback during commit,
271
 
            it may return None for the second element of the tuple.
272
 
        """
273
 
        return (self.get_file(file_id, path), None)
274
 
 
275
265
    def get_file_text(self, file_id, path=None):
276
266
        """Return the byte content of a file.
277
267
 
291
281
 
292
282
        :param file_id: The file_id of the file.
293
283
        :param path: The path of the file.
294
 
 
295
284
        If both file_id and path are supplied, an implementation may use
296
285
        either one.
297
286
        """
298
287
        return osutils.split_lines(self.get_file_text(file_id, path))
299
288
 
300
 
    def get_file_sha1(self, file_id, path=None, stat_value=None):
301
 
        """Return the SHA1 file for a file.
302
 
 
303
 
        :param file_id: The handle for this file.
304
 
        :param path: The path that this file can be found at.
305
 
            These must point to the same object.
306
 
        :param stat_value: Optional stat value for the object
307
 
        """
308
 
        raise NotImplementedError(self.get_file_sha1)
309
 
 
310
289
    def get_file_mtime(self, file_id, path=None):
311
290
        """Return the modification time for a file.
312
291
 
326
305
        raise NotImplementedError(self.get_file_size)
327
306
 
328
307
    def get_file_by_path(self, path):
329
 
        raise NotImplementedError(self.get_file_by_path)
330
 
 
331
 
    def is_executable(self, file_id, path=None):
332
 
        """Check if a file is executable.
333
 
 
334
 
        :param file_id: The handle for this file.
335
 
        :param path: The path that this file can be found at.
336
 
            These must point to the same object.
337
 
        """
338
 
        raise NotImplementedError(self.is_executable)
 
308
        return self.get_file(self._inventory.path2id(path), path)
339
309
 
340
310
    def iter_files_bytes(self, desired_files):
341
311
        """Iterate through file contents.
363
333
            cur_file = (self.get_file_text(file_id),)
364
334
            yield identifier, cur_file
365
335
 
366
 
    def get_symlink_target(self, file_id, path=None):
 
336
    def get_symlink_target(self, file_id):
367
337
        """Get the target for a given file_id.
368
338
 
369
339
        It is assumed that the caller already knows that file_id is referencing
370
340
        a symlink.
371
341
        :param file_id: Handle for the symlink entry.
372
 
        :param path: The path of the file.
373
 
        If both file_id and path are supplied, an implementation may use
374
 
        either one.
375
342
        :return: The path the symlink points to.
376
343
        """
377
344
        raise NotImplementedError(self.get_symlink_target)
378
345
 
 
346
    def get_canonical_inventory_paths(self, paths):
 
347
        """Like get_canonical_inventory_path() but works on multiple items.
 
348
 
 
349
        :param paths: A sequence of paths relative to the root of the tree.
 
350
        :return: A list of paths, with each item the corresponding input path
 
351
        adjusted to account for existing elements that match case
 
352
        insensitively.
 
353
        """
 
354
        return list(self._yield_canonical_inventory_paths(paths))
 
355
 
 
356
    def get_canonical_inventory_path(self, path):
 
357
        """Returns the first inventory item that case-insensitively matches path.
 
358
 
 
359
        If a path matches exactly, it is returned. If no path matches exactly
 
360
        but more than one path matches case-insensitively, it is implementation
 
361
        defined which is returned.
 
362
 
 
363
        If no path matches case-insensitively, the input path is returned, but
 
364
        with as many path entries that do exist changed to their canonical
 
365
        form.
 
366
 
 
367
        If you need to resolve many names from the same tree, you should
 
368
        use get_canonical_inventory_paths() to avoid O(N) behaviour.
 
369
 
 
370
        :param path: A paths relative to the root of the tree.
 
371
        :return: The input path adjusted to account for existing elements
 
372
        that match case insensitively.
 
373
        """
 
374
        return self._yield_canonical_inventory_paths([path]).next()
 
375
 
 
376
    def _yield_canonical_inventory_paths(self, paths):
 
377
        for path in paths:
 
378
            # First, if the path as specified exists exactly, just use it.
 
379
            if self.path2id(path) is not None:
 
380
                yield path
 
381
                continue
 
382
            # go walkin...
 
383
            cur_id = self.get_root_id()
 
384
            cur_path = ''
 
385
            bit_iter = iter(path.split("/"))
 
386
            for elt in bit_iter:
 
387
                lelt = elt.lower()
 
388
                for child in self.iter_children(cur_id):
 
389
                    try:
 
390
                        child_base = os.path.basename(self.id2path(child))
 
391
                        if child_base.lower() == lelt:
 
392
                            cur_id = child
 
393
                            cur_path = osutils.pathjoin(cur_path, child_base)
 
394
                            break
 
395
                    except NoSuchId:
 
396
                        # before a change is committed we can see this error...
 
397
                        continue
 
398
                else:
 
399
                    # got to the end of this directory and no entries matched.
 
400
                    # Return what matched so far, plus the rest as specified.
 
401
                    cur_path = osutils.pathjoin(cur_path, elt, *list(bit_iter))
 
402
                    break
 
403
            yield cur_path
 
404
        # all done.
 
405
 
379
406
    def get_root_id(self):
380
407
        """Return the file_id for the root of this tree."""
381
408
        raise NotImplementedError(self.get_root_id)
395
422
        raise NotImplementedError(self.annotate_iter)
396
423
 
397
424
    def _get_plan_merge_data(self, file_id, other, base):
398
 
        from bzrlib import versionedfile
 
425
        from bzrlib import merge, versionedfile
399
426
        vf = versionedfile._PlanMergeVersionedFile(file_id)
400
427
        last_revision_a = self._get_file_revision(file_id, vf, 'this:')
401
428
        last_revision_b = other._get_file_revision(file_id, vf, 'other:')
439
466
            except errors.NoSuchRevisionInTree:
440
467
                yield self.repository.revision_tree(revision_id)
441
468
 
 
469
    @staticmethod
 
470
    def _file_revision(revision_tree, file_id):
 
471
        """Determine the revision associated with a file in a given tree."""
 
472
        revision_tree.lock_read()
 
473
        try:
 
474
            return revision_tree.inventory[file_id].revision
 
475
        finally:
 
476
            revision_tree.unlock()
 
477
 
442
478
    def _get_file_revision(self, file_id, vf, tree_revision):
443
479
        """Ensure that file_id, tree_revision is in vf to plan the merge."""
444
480
 
445
481
        if getattr(self, '_repository', None) is None:
446
482
            last_revision = tree_revision
447
 
            parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
 
483
            parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
448
484
                self._iter_parent_trees()]
449
485
            vf.add_lines((file_id, last_revision), parent_keys,
450
 
                         self.get_file_lines(file_id))
 
486
                         self.get_file(file_id).readlines())
451
487
            repo = self.branch.repository
452
488
            base_vf = repo.texts
453
489
        else:
454
 
            last_revision = self.get_file_revision(file_id)
 
490
            last_revision = self._file_revision(self, file_id)
455
491
            base_vf = self._repository.texts
456
492
        if base_vf not in vf.fallback_versionedfiles:
457
493
            vf.fallback_versionedfiles.append(base_vf)
458
494
        return last_revision
459
495
 
 
496
    inventory = property(_get_inventory,
 
497
                         doc="Inventory of this Tree")
 
498
 
460
499
    def _check_retrieved(self, ie, f):
461
500
        if not __debug__:
462
501
            return
463
 
        fp = osutils.fingerprint_file(f)
 
502
        fp = fingerprint_file(f)
464
503
        f.seek(0)
465
504
 
466
505
        if ie.text_size is not None:
467
506
            if ie.text_size != fp['size']:
468
 
                raise errors.BzrError(
469
 
                        "mismatched size for file %r in %r" %
470
 
                        (ie.file_id, self._store),
 
507
                raise BzrError("mismatched size for file %r in %r" % (ie.file_id, self._store),
471
508
                        ["inventory expects %d bytes" % ie.text_size,
472
509
                         "file is actually %d bytes" % fp['size'],
473
510
                         "store is probably damaged/corrupt"])
474
511
 
475
512
        if ie.text_sha1 != fp['sha1']:
476
 
            raise errors.BzrError("wrong SHA-1 for file %r in %r" %
477
 
                    (ie.file_id, self._store),
 
513
            raise BzrError("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
478
514
                    ["inventory expects %s" % ie.text_sha1,
479
515
                     "file is actually %s" % fp['sha1'],
480
516
                     "store is probably damaged/corrupt"])
481
517
 
 
518
    @needs_read_lock
482
519
    def path2id(self, path):
483
520
        """Return the id for path in this tree."""
484
 
        raise NotImplementedError(self.path2id)
 
521
        return self._inventory.path2id(path)
485
522
 
486
523
    def paths2ids(self, paths, trees=[], require_versioned=True):
487
524
        """Return all the ids that can be reached by walking from paths.
508
545
            yield child.file_id
509
546
 
510
547
    def lock_read(self):
511
 
        """Lock this tree for multiple read only operations.
512
 
        
513
 
        :return: A bzrlib.lock.LogicalLockResult.
514
 
        """
515
548
        pass
516
549
 
517
550
    def revision_tree(self, revision_id):
544
577
 
545
578
        :return: set of paths.
546
579
        """
547
 
        raise NotImplementedError(self.filter_unversioned_files)
 
580
        # NB: we specifically *don't* call self.has_filename, because for
 
581
        # WorkingTrees that can indicate files that exist on disk but that
 
582
        # are not versioned.
 
583
        pred = self.inventory.has_filename
 
584
        return set((p for p in paths if not pred(p)))
548
585
 
549
586
    def walkdirs(self, prefix=""):
550
587
        """Walk the contents of this tree from path down.
602
639
        prefs = self.iter_search_rules([path], filter_pref_names).next()
603
640
        stk = filters._get_filter_stack_for(prefs)
604
641
        if 'filters' in debug.debug_flags:
605
 
            trace.note("*** %s content-filter: %s => %r" % (path,prefs,stk))
 
642
            note("*** %s content-filter: %s => %r" % (path,prefs,stk))
606
643
        return stk
607
644
 
608
645
    def _content_filter_stack_provider(self):
620
657
            return None
621
658
 
622
659
    def iter_search_rules(self, path_names, pref_names=None,
623
 
        _default_searcher=None):
 
660
        _default_searcher=rules._per_user_searcher):
624
661
        """Find the preferences for filenames in a tree.
625
662
 
626
663
        :param path_names: an iterable of paths to find attributes for.
630
667
        :return: an iterator of tuple sequences, one per path-name.
631
668
          See _RulesSearcher.get_items for details on the tuple sequence.
632
669
        """
633
 
        if _default_searcher is None:
634
 
            _default_searcher = rules._per_user_searcher
635
670
        searcher = self._get_rules_searcher(_default_searcher)
636
671
        if searcher is not None:
637
672
            if pref_names is not None:
641
676
                for path in path_names:
642
677
                    yield searcher.get_items(path)
643
678
 
 
679
    @needs_read_lock
644
680
    def _get_rules_searcher(self, default_searcher):
645
681
        """Get the RulesSearcher for this tree given the default one."""
646
682
        searcher = default_searcher
647
683
        return searcher
648
684
 
649
685
 
650
 
class InventoryTree(Tree):
651
 
    """A tree that relies on an inventory for its metadata.
652
 
 
653
 
    Trees contain an `Inventory` object, and also know how to retrieve
654
 
    file texts mentioned in the inventory, either from a working
655
 
    directory or from a store.
656
 
 
657
 
    It is possible for trees to contain files that are not described
658
 
    in their inventory or vice versa; for this use `filenames()`.
659
 
 
660
 
    Subclasses should set the _inventory attribute, which is considered
661
 
    private to external API users.
 
686
######################################################################
 
687
# diff
 
688
 
 
689
# TODO: Merge these two functions into a single one that can operate
 
690
# on either a whole tree or a set of files.
 
691
 
 
692
# TODO: Return the diff in order by filename, not by category or in
 
693
# random order.  Can probably be done by lock-stepping through the
 
694
# filenames from both trees.
 
695
 
 
696
 
 
697
def file_status(filename, old_tree, new_tree):
 
698
    """Return single-letter status, old and new names for a file.
 
699
 
 
700
    The complexity here is in deciding how to represent renames;
 
701
    many complex cases are possible.
662
702
    """
663
 
 
664
 
    def get_canonical_inventory_paths(self, paths):
665
 
        """Like get_canonical_inventory_path() but works on multiple items.
666
 
 
667
 
        :param paths: A sequence of paths relative to the root of the tree.
668
 
        :return: A list of paths, with each item the corresponding input path
669
 
        adjusted to account for existing elements that match case
670
 
        insensitively.
671
 
        """
672
 
        return list(self._yield_canonical_inventory_paths(paths))
673
 
 
674
 
    def get_canonical_inventory_path(self, path):
675
 
        """Returns the first inventory item that case-insensitively matches path.
676
 
 
677
 
        If a path matches exactly, it is returned. If no path matches exactly
678
 
        but more than one path matches case-insensitively, it is implementation
679
 
        defined which is returned.
680
 
 
681
 
        If no path matches case-insensitively, the input path is returned, but
682
 
        with as many path entries that do exist changed to their canonical
683
 
        form.
684
 
 
685
 
        If you need to resolve many names from the same tree, you should
686
 
        use get_canonical_inventory_paths() to avoid O(N) behaviour.
687
 
 
688
 
        :param path: A paths relative to the root of the tree.
689
 
        :return: The input path adjusted to account for existing elements
690
 
        that match case insensitively.
691
 
        """
692
 
        return self._yield_canonical_inventory_paths([path]).next()
693
 
 
694
 
    def _yield_canonical_inventory_paths(self, paths):
695
 
        for path in paths:
696
 
            # First, if the path as specified exists exactly, just use it.
697
 
            if self.path2id(path) is not None:
698
 
                yield path
699
 
                continue
700
 
            # go walkin...
701
 
            cur_id = self.get_root_id()
702
 
            cur_path = ''
703
 
            bit_iter = iter(path.split("/"))
704
 
            for elt in bit_iter:
705
 
                lelt = elt.lower()
706
 
                new_path = None
707
 
                for child in self.iter_children(cur_id):
708
 
                    try:
709
 
                        # XXX: it seem like if the child is known to be in the
710
 
                        # tree, we shouldn't need to go from its id back to
711
 
                        # its path -- mbp 2010-02-11
712
 
                        #
713
 
                        # XXX: it seems like we could be more efficient
714
 
                        # by just directly looking up the original name and
715
 
                        # only then searching all children; also by not
716
 
                        # chopping paths so much. -- mbp 2010-02-11
717
 
                        child_base = os.path.basename(self.id2path(child))
718
 
                        if (child_base == elt):
719
 
                            # if we found an exact match, we can stop now; if
720
 
                            # we found an approximate match we need to keep
721
 
                            # searching because there might be an exact match
722
 
                            # later.  
723
 
                            cur_id = child
724
 
                            new_path = osutils.pathjoin(cur_path, child_base)
725
 
                            break
726
 
                        elif child_base.lower() == lelt:
727
 
                            cur_id = child
728
 
                            new_path = osutils.pathjoin(cur_path, child_base)
729
 
                    except errors.NoSuchId:
730
 
                        # before a change is committed we can see this error...
731
 
                        continue
732
 
                if new_path:
733
 
                    cur_path = new_path
734
 
                else:
735
 
                    # got to the end of this directory and no entries matched.
736
 
                    # Return what matched so far, plus the rest as specified.
737
 
                    cur_path = osutils.pathjoin(cur_path, elt, *list(bit_iter))
738
 
                    break
739
 
            yield cur_path
740
 
        # all done.
741
 
 
742
 
    def _get_inventory(self):
743
 
        return self._inventory
744
 
 
745
 
    inventory = property(_get_inventory,
746
 
                         doc="Inventory of this Tree")
747
 
 
748
 
    @needs_read_lock
749
 
    def path2id(self, path):
750
 
        """Return the id for path in this tree."""
751
 
        return self._inventory.path2id(path)
752
 
 
753
 
    def id2path(self, file_id):
754
 
        """Return the path for a file id.
755
 
 
756
 
        :raises NoSuchId:
757
 
        """
758
 
        return self.inventory.id2path(file_id)
759
 
 
760
 
    def has_id(self, file_id):
761
 
        return self.inventory.has_id(file_id)
762
 
 
763
 
    def has_or_had_id(self, file_id):
764
 
        return self.inventory.has_id(file_id)
765
 
 
766
 
    def all_file_ids(self):
767
 
        return set(self.inventory)
768
 
 
769
 
    @deprecated_method(deprecated_in((2, 4, 0)))
770
 
    def __iter__(self):
771
 
        return iter(self.inventory)
772
 
 
773
 
    def filter_unversioned_files(self, paths):
774
 
        """Filter out paths that are versioned.
775
 
 
776
 
        :return: set of paths.
777
 
        """
778
 
        # NB: we specifically *don't* call self.has_filename, because for
779
 
        # WorkingTrees that can indicate files that exist on disk but that
780
 
        # are not versioned.
781
 
        pred = self.inventory.has_filename
782
 
        return set((p for p in paths if not pred(p)))
783
 
 
784
 
    @needs_read_lock
785
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
786
 
        """Walk the tree in 'by_dir' order.
787
 
 
788
 
        This will yield each entry in the tree as a (path, entry) tuple.
789
 
        The order that they are yielded is:
790
 
 
791
 
        See Tree.iter_entries_by_dir for details.
792
 
 
793
 
        :param yield_parents: If True, yield the parents from the root leading
794
 
            down to specific_file_ids that have been requested. This has no
795
 
            impact if specific_file_ids is None.
796
 
        """
797
 
        return self.inventory.iter_entries_by_dir(
798
 
            specific_file_ids=specific_file_ids, yield_parents=yield_parents)
799
 
 
800
 
    def get_file_by_path(self, path):
801
 
        return self.get_file(self._inventory.path2id(path), path)
 
703
    old_inv = old_tree.inventory
 
704
    new_inv = new_tree.inventory
 
705
    new_id = new_inv.path2id(filename)
 
706
    old_id = old_inv.path2id(filename)
 
707
 
 
708
    if not new_id and not old_id:
 
709
        # easy: doesn't exist in either; not versioned at all
 
710
        if new_tree.is_ignored(filename):
 
711
            return 'I', None, None
 
712
        else:
 
713
            return '?', None, None
 
714
    elif new_id:
 
715
        # There is now a file of this name, great.
 
716
        pass
 
717
    else:
 
718
        # There is no longer a file of this name, but we can describe
 
719
        # what happened to the file that used to have
 
720
        # this name.  There are two possibilities: either it was
 
721
        # deleted entirely, or renamed.
 
722
        if new_inv.has_id(old_id):
 
723
            return 'X', old_inv.id2path(old_id), new_inv.id2path(old_id)
 
724
        else:
 
725
            return 'D', old_inv.id2path(old_id), None
 
726
 
 
727
    # if the file_id is new in this revision, it is added
 
728
    if new_id and not old_inv.has_id(new_id):
 
729
        return 'A'
 
730
 
 
731
    # if there used to be a file of this name, but that ID has now
 
732
    # disappeared, it is deleted
 
733
    if old_id and not new_inv.has_id(old_id):
 
734
        return 'D'
 
735
 
 
736
    return 'wtf?'
 
737
 
 
738
 
 
739
@deprecated_function(deprecated_in((1, 9, 0)))
 
740
def find_renames(old_inv, new_inv):
 
741
    for file_id in old_inv:
 
742
        if file_id not in new_inv:
 
743
            continue
 
744
        old_name = old_inv.id2path(file_id)
 
745
        new_name = new_inv.id2path(file_id)
 
746
        if old_name != new_name:
 
747
            yield (old_name, new_name)
802
748
 
803
749
 
804
750
def find_ids_across_trees(filenames, trees, require_versioned=True):
811
757
        None)
812
758
    :param trees: The trees to find file_ids within
813
759
    :param require_versioned: if true, all specified filenames must occur in
814
 
        at least one tree.
 
760
    at least one tree.
815
761
    :return: a set of file ids for the specified filenames and their children.
816
762
    """
817
763
    if not filenames:
864
810
        new_pending = set()
865
811
        for file_id in pending:
866
812
            for tree in trees:
867
 
                if not tree.has_or_had_id(file_id):
 
813
                if not tree.has_id(file_id):
868
814
                    continue
869
815
                for child_id in tree.iter_children(file_id):
870
816
                    if child_id not in interesting_ids:
885
831
    will pass through to InterTree as appropriate.
886
832
    """
887
833
 
888
 
    # Formats that will be used to test this InterTree. If both are
889
 
    # None, this InterTree will not be tested (e.g. because a complex
890
 
    # setup is required)
891
 
    _matching_from_tree_format = None
892
 
    _matching_to_tree_format = None
893
 
 
894
834
    _optimisers = []
895
835
 
896
 
    @classmethod
897
 
    def is_compatible(kls, source, target):
898
 
        # The default implementation is naive and uses the public API, so
899
 
        # it works for all trees.
900
 
        return True
901
 
 
902
 
    def _changes_from_entries(self, source_entry, target_entry,
903
 
        source_path=None, target_path=None):
904
 
        """Generate a iter_changes tuple between source_entry and target_entry.
905
 
 
906
 
        :param source_entry: An inventory entry from self.source, or None.
907
 
        :param target_entry: An inventory entry from self.target, or None.
908
 
        :param source_path: The path of source_entry, if known. If not known
909
 
            it will be looked up.
910
 
        :param target_path: The path of target_entry, if known. If not known
911
 
            it will be looked up.
912
 
        :return: A tuple, item 0 of which is an iter_changes result tuple, and
913
 
            item 1 is True if there are any changes in the result tuple.
914
 
        """
915
 
        if source_entry is None:
916
 
            if target_entry is None:
917
 
                return None
918
 
            file_id = target_entry.file_id
919
 
        else:
920
 
            file_id = source_entry.file_id
921
 
        if source_entry is not None:
922
 
            source_versioned = True
923
 
            source_name = source_entry.name
924
 
            source_parent = source_entry.parent_id
925
 
            if source_path is None:
926
 
                source_path = self.source.id2path(file_id)
927
 
            source_kind, source_executable, source_stat = \
928
 
                self.source._comparison_data(source_entry, source_path)
929
 
        else:
930
 
            source_versioned = False
931
 
            source_name = None
932
 
            source_parent = None
933
 
            source_kind = None
934
 
            source_executable = None
935
 
        if target_entry is not None:
936
 
            target_versioned = True
937
 
            target_name = target_entry.name
938
 
            target_parent = target_entry.parent_id
939
 
            if target_path is None:
940
 
                target_path = self.target.id2path(file_id)
941
 
            target_kind, target_executable, target_stat = \
942
 
                self.target._comparison_data(target_entry, target_path)
943
 
        else:
944
 
            target_versioned = False
945
 
            target_name = None
946
 
            target_parent = None
947
 
            target_kind = None
948
 
            target_executable = None
949
 
        versioned = (source_versioned, target_versioned)
950
 
        kind = (source_kind, target_kind)
951
 
        changed_content = False
952
 
        if source_kind != target_kind:
953
 
            changed_content = True
954
 
        elif source_kind == 'file':
955
 
            if (self.source.get_file_sha1(file_id, source_path, source_stat) !=
956
 
                self.target.get_file_sha1(file_id, target_path, target_stat)):
957
 
                changed_content = True
958
 
        elif source_kind == 'symlink':
959
 
            if (self.source.get_symlink_target(file_id) !=
960
 
                self.target.get_symlink_target(file_id)):
961
 
                changed_content = True
962
 
            # XXX: Yes, the indentation below is wrong. But fixing it broke
963
 
            # test_merge.TestMergerEntriesLCAOnDisk.
964
 
            # test_nested_tree_subtree_renamed_and_modified. We'll wait for
965
 
            # the fix from bzr.dev -- vila 2009026
966
 
            elif source_kind == 'tree-reference':
967
 
                if (self.source.get_reference_revision(file_id, source_path)
968
 
                    != self.target.get_reference_revision(file_id, target_path)):
969
 
                    changed_content = True
970
 
        parent = (source_parent, target_parent)
971
 
        name = (source_name, target_name)
972
 
        executable = (source_executable, target_executable)
973
 
        if (changed_content is not False or versioned[0] != versioned[1]
974
 
            or parent[0] != parent[1] or name[0] != name[1] or
975
 
            executable[0] != executable[1]):
976
 
            changes = True
977
 
        else:
978
 
            changes = False
979
 
        return (file_id, (source_path, target_path), changed_content,
980
 
                versioned, parent, name, kind, executable), changes
981
 
 
982
836
    @needs_read_lock
983
837
    def compare(self, want_unchanged=False, specific_files=None,
984
838
        extra_trees=None, require_versioned=False, include_root=False,
999
853
            a PathsNotVersionedError will be thrown.
1000
854
        :param want_unversioned: Scan for unversioned paths.
1001
855
        """
 
856
        # NB: show_status depends on being able to pass in non-versioned files
 
857
        # and report them as unknown
1002
858
        trees = (self.source,)
1003
859
        if extra_trees is not None:
1004
860
            trees = trees + tuple(extra_trees)
1009
865
            # All files are unversioned, so just return an empty delta
1010
866
            # _compare_trees would think we want a complete delta
1011
867
            result = delta.TreeDelta()
1012
 
            fake_entry = inventory.InventoryFile('unused', 'unused', 'unused')
 
868
            fake_entry = InventoryFile('unused', 'unused', 'unused')
1013
869
            result.unversioned = [(path, None,
1014
870
                self.target._comparison_data(fake_entry, path)[0]) for path in
1015
871
                specific_files]
1045
901
        :param require_versioned: Raise errors.PathsNotVersionedError if a
1046
902
            path in the specific_files list is not versioned in one of
1047
903
            source, target or extra_trees.
1048
 
        :param specific_files: An optional list of file paths to restrict the
1049
 
            comparison to. When mapping filenames to ids, all matches in all
1050
 
            trees (including optional extra_trees) are used, and all children
1051
 
            of matched directories are included. The parents in the target tree
1052
 
            of the specific files up to and including the root of the tree are
1053
 
            always evaluated for changes too.
1054
904
        :param want_unversioned: Should unversioned files be returned in the
1055
905
            output. An unversioned file is defined as one with (False, False)
1056
906
            for the versioned pair.
1058
908
        lookup_trees = [self.source]
1059
909
        if extra_trees:
1060
910
             lookup_trees.extend(extra_trees)
1061
 
        # The ids of items we need to examine to insure delta consistency.
1062
 
        precise_file_ids = set()
1063
 
        changed_file_ids = []
1064
911
        if specific_files == []:
1065
912
            specific_file_ids = []
1066
913
        else:
1067
914
            specific_file_ids = self.target.paths2ids(specific_files,
1068
915
                lookup_trees, require_versioned=require_versioned)
1069
 
        if specific_files is not None:
1070
 
            # reparented or added entries must have their parents included
1071
 
            # so that valid deltas can be created. The seen_parents set
1072
 
            # tracks the parents that we need to have.
1073
 
            # The seen_dirs set tracks directory entries we've yielded.
1074
 
            # After outputting version object in to_entries we set difference
1075
 
            # the two seen sets and start checking parents.
1076
 
            seen_parents = set()
1077
 
            seen_dirs = set()
1078
916
        if want_unversioned:
1079
917
            all_unversioned = sorted([(p.split('/'), p) for p in
1080
918
                                     self.target.extras()
1081
919
                if specific_files is None or
1082
920
                    osutils.is_inside_any(specific_files, p)])
1083
 
            all_unversioned = collections.deque(all_unversioned)
 
921
            all_unversioned = deque(all_unversioned)
1084
922
        else:
1085
 
            all_unversioned = collections.deque()
 
923
            all_unversioned = deque()
1086
924
        to_paths = {}
1087
925
        from_entries_by_dir = list(self.source.iter_entries_by_dir(
1088
926
            specific_file_ids=specific_file_ids))
1094
932
        # the unversioned path lookup only occurs on real trees - where there
1095
933
        # can be extras. So the fake_entry is solely used to look up
1096
934
        # executable it values when execute is not supported.
1097
 
        fake_entry = inventory.InventoryFile('unused', 'unused', 'unused')
1098
 
        for target_path, target_entry in to_entries_by_dir:
1099
 
            while (all_unversioned and
1100
 
                all_unversioned[0][0] < target_path.split('/')):
 
935
        fake_entry = InventoryFile('unused', 'unused', 'unused')
 
936
        for to_path, to_entry in to_entries_by_dir:
 
937
            while all_unversioned and all_unversioned[0][0] < to_path.split('/'):
1101
938
                unversioned_path = all_unversioned.popleft()
1102
 
                target_kind, target_executable, target_stat = \
 
939
                to_kind, to_executable, to_stat = \
1103
940
                    self.target._comparison_data(fake_entry, unversioned_path[1])
1104
941
                yield (None, (None, unversioned_path[1]), True, (False, False),
1105
942
                    (None, None),
1106
943
                    (None, unversioned_path[0][-1]),
1107
 
                    (None, target_kind),
1108
 
                    (None, target_executable))
1109
 
            source_path, source_entry = from_data.get(target_entry.file_id,
1110
 
                (None, None))
1111
 
            result, changes = self._changes_from_entries(source_entry,
1112
 
                target_entry, source_path=source_path, target_path=target_path)
1113
 
            to_paths[result[0]] = result[1][1]
 
944
                    (None, to_kind),
 
945
                    (None, to_executable))
 
946
            file_id = to_entry.file_id
 
947
            to_paths[file_id] = to_path
1114
948
            entry_count += 1
1115
 
            if result[3][0]:
 
949
            changed_content = False
 
950
            from_path, from_entry = from_data.get(file_id, (None, None))
 
951
            from_versioned = (from_entry is not None)
 
952
            if from_entry is not None:
 
953
                from_versioned = True
 
954
                from_name = from_entry.name
 
955
                from_parent = from_entry.parent_id
 
956
                from_kind, from_executable, from_stat = \
 
957
                    self.source._comparison_data(from_entry, from_path)
1116
958
                entry_count += 1
 
959
            else:
 
960
                from_versioned = False
 
961
                from_kind = None
 
962
                from_parent = None
 
963
                from_name = None
 
964
                from_executable = None
 
965
            versioned = (from_versioned, True)
 
966
            to_kind, to_executable, to_stat = \
 
967
                self.target._comparison_data(to_entry, to_path)
 
968
            kind = (from_kind, to_kind)
 
969
            if kind[0] != kind[1]:
 
970
                changed_content = True
 
971
            elif from_kind == 'file':
 
972
                if (self.source.get_file_sha1(file_id, from_path, from_stat) !=
 
973
                    self.target.get_file_sha1(file_id, to_path, to_stat)):
 
974
                    changed_content = True
 
975
            elif from_kind == 'symlink':
 
976
                if (self.source.get_symlink_target(file_id) !=
 
977
                    self.target.get_symlink_target(file_id)):
 
978
                    changed_content = True
 
979
                # XXX: Yes, the indentation below is wrong. But fixing it broke
 
980
                # test_merge.TestMergerEntriesLCAOnDisk.
 
981
                # test_nested_tree_subtree_renamed_and_modified. We'll wait for
 
982
                # the fix from bzr.dev -- vila 2009026
 
983
                elif from_kind == 'tree-reference':
 
984
                    if (self.source.get_reference_revision(file_id, from_path)
 
985
                        != self.target.get_reference_revision(file_id, to_path)):
 
986
                        changed_content = True
 
987
            parent = (from_parent, to_entry.parent_id)
 
988
            name = (from_name, to_entry.name)
 
989
            executable = (from_executable, to_executable)
1117
990
            if pb is not None:
1118
991
                pb.update('comparing files', entry_count, num_entries)
1119
 
            if changes or include_unchanged:
1120
 
                if specific_file_ids is not None:
1121
 
                    new_parent_id = result[4][1]
1122
 
                    precise_file_ids.add(new_parent_id)
1123
 
                    changed_file_ids.append(result[0])
1124
 
                yield result
1125
 
            # Ensure correct behaviour for reparented/added specific files.
1126
 
            if specific_files is not None:
1127
 
                # Record output dirs
1128
 
                if result[6][1] == 'directory':
1129
 
                    seen_dirs.add(result[0])
1130
 
                # Record parents of reparented/added entries.
1131
 
                versioned = result[3]
1132
 
                parents = result[4]
1133
 
                if not versioned[0] or parents[0] != parents[1]:
1134
 
                    seen_parents.add(parents[1])
 
992
            if (changed_content is not False or versioned[0] != versioned[1]
 
993
                or parent[0] != parent[1] or name[0] != name[1] or
 
994
                executable[0] != executable[1] or include_unchanged):
 
995
                yield (file_id, (from_path, to_path), changed_content,
 
996
                    versioned, parent, name, kind, executable)
 
997
 
1135
998
        while all_unversioned:
1136
999
            # yield any trailing unversioned paths
1137
1000
            unversioned_path = all_unversioned.popleft()
1142
1005
                (None, unversioned_path[0][-1]),
1143
1006
                (None, to_kind),
1144
1007
                (None, to_executable))
1145
 
        # Yield all remaining source paths
 
1008
 
 
1009
        def get_to_path(to_entry):
 
1010
            if to_entry.parent_id is None:
 
1011
                to_path = '' # the root
 
1012
            else:
 
1013
                if to_entry.parent_id not in to_paths:
 
1014
                    # recurse up
 
1015
                    return get_to_path(self.target.inventory[to_entry.parent_id])
 
1016
                to_path = osutils.pathjoin(to_paths[to_entry.parent_id],
 
1017
                                           to_entry.name)
 
1018
            to_paths[to_entry.file_id] = to_path
 
1019
            return to_path
 
1020
 
1146
1021
        for path, from_entry in from_entries_by_dir:
1147
1022
            file_id = from_entry.file_id
1148
1023
            if file_id in to_paths:
1149
1024
                # already returned
1150
1025
                continue
1151
 
            if not self.target.has_id(file_id):
 
1026
            if not file_id in self.target.all_file_ids():
1152
1027
                # common case - paths we have not emitted are not present in
1153
1028
                # target.
1154
1029
                to_path = None
1155
1030
            else:
1156
 
                to_path = self.target.id2path(file_id)
 
1031
                to_path = get_to_path(self.target.inventory[file_id])
1157
1032
            entry_count += 1
1158
1033
            if pb is not None:
1159
1034
                pb.update('comparing files', entry_count, num_entries)
1166
1041
            executable = (from_executable, None)
1167
1042
            changed_content = from_kind is not None
1168
1043
            # the parent's path is necessarily known at this point.
1169
 
            changed_file_ids.append(file_id)
1170
1044
            yield(file_id, (path, to_path), changed_content, versioned, parent,
1171
1045
                  name, kind, executable)
1172
 
        changed_file_ids = set(changed_file_ids)
1173
 
        if specific_file_ids is not None:
1174
 
            for result in self._handle_precise_ids(precise_file_ids,
1175
 
                changed_file_ids):
1176
 
                yield result
1177
 
 
1178
 
    def _get_entry(self, tree, file_id):
1179
 
        """Get an inventory entry from a tree, with missing entries as None.
1180
 
 
1181
 
        If the tree raises NotImplementedError on accessing .inventory, then
1182
 
        this is worked around using iter_entries_by_dir on just the file id
1183
 
        desired.
1184
 
 
1185
 
        :param tree: The tree to lookup the entry in.
1186
 
        :param file_id: The file_id to lookup.
1187
 
        """
1188
 
        try:
1189
 
            inventory = tree.inventory
1190
 
        except NotImplementedError:
1191
 
            # No inventory available.
1192
 
            try:
1193
 
                iterator = tree.iter_entries_by_dir(specific_file_ids=[file_id])
1194
 
                return iterator.next()[1]
1195
 
            except StopIteration:
1196
 
                return None
1197
 
        else:
1198
 
            try:
1199
 
                return inventory[file_id]
1200
 
            except errors.NoSuchId:
1201
 
                return None
1202
 
 
1203
 
    def _handle_precise_ids(self, precise_file_ids, changed_file_ids,
1204
 
        discarded_changes=None):
1205
 
        """Fill out a partial iter_changes to be consistent.
1206
 
 
1207
 
        :param precise_file_ids: The file ids of parents that were seen during
1208
 
            the iter_changes.
1209
 
        :param changed_file_ids: The file ids of already emitted items.
1210
 
        :param discarded_changes: An optional dict of precalculated
1211
 
            iter_changes items which the partial iter_changes had not output
1212
 
            but had calculated.
1213
 
        :return: A generator of iter_changes items to output.
1214
 
        """
1215
 
        # process parents of things that had changed under the users
1216
 
        # requested paths to prevent incorrect paths or parent ids which
1217
 
        # aren't in the tree.
1218
 
        while precise_file_ids:
1219
 
            precise_file_ids.discard(None)
1220
 
            # Don't emit file_ids twice
1221
 
            precise_file_ids.difference_update(changed_file_ids)
1222
 
            if not precise_file_ids:
1223
 
                break
1224
 
            # If the there was something at a given output path in source, we
1225
 
            # have to include the entry from source in the delta, or we would
1226
 
            # be putting this entry into a used path.
1227
 
            paths = []
1228
 
            for parent_id in precise_file_ids:
1229
 
                try:
1230
 
                    paths.append(self.target.id2path(parent_id))
1231
 
                except errors.NoSuchId:
1232
 
                    # This id has been dragged in from the source by delta
1233
 
                    # expansion and isn't present in target at all: we don't
1234
 
                    # need to check for path collisions on it.
1235
 
                    pass
1236
 
            for path in paths:
1237
 
                old_id = self.source.path2id(path)
1238
 
                precise_file_ids.add(old_id)
1239
 
            precise_file_ids.discard(None)
1240
 
            current_ids = precise_file_ids
1241
 
            precise_file_ids = set()
1242
 
            # We have to emit all of precise_file_ids that have been altered.
1243
 
            # We may have to output the children of some of those ids if any
1244
 
            # directories have stopped being directories.
1245
 
            for file_id in current_ids:
1246
 
                # Examine file_id
1247
 
                if discarded_changes:
1248
 
                    result = discarded_changes.get(file_id)
1249
 
                    old_entry = None
1250
 
                else:
1251
 
                    result = None
1252
 
                if result is None:
1253
 
                    old_entry = self._get_entry(self.source, file_id)
1254
 
                    new_entry = self._get_entry(self.target, file_id)
1255
 
                    result, changes = self._changes_from_entries(
1256
 
                        old_entry, new_entry)
1257
 
                else:
1258
 
                    changes = True
1259
 
                # Get this parents parent to examine.
1260
 
                new_parent_id = result[4][1]
1261
 
                precise_file_ids.add(new_parent_id)
1262
 
                if changes:
1263
 
                    if (result[6][0] == 'directory' and
1264
 
                        result[6][1] != 'directory'):
1265
 
                        # This stopped being a directory, the old children have
1266
 
                        # to be included.
1267
 
                        if old_entry is None:
1268
 
                            # Reusing a discarded change.
1269
 
                            old_entry = self._get_entry(self.source, file_id)
1270
 
                        for child in old_entry.children.values():
1271
 
                            precise_file_ids.add(child.file_id)
1272
 
                    changed_file_ids.add(result[0])
1273
 
                    yield result
1274
 
 
1275
 
 
1276
 
InterTree.register_optimiser(InterTree)
1277
1046
 
1278
1047
 
1279
1048
class MultiWalker(object):