~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/graph.py

  • Committer: Martin Pool
  • Date: 2009-07-27 06:28:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4587.
  • Revision ID: mbp@sourcefrog.net-20090727062835-o66p8it658tq1sma
Add CountedLock.get_physical_lock_status

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007, 2008, 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import time
18
18
 
20
20
    debug,
21
21
    errors,
22
22
    revision,
23
 
    symbol_versioning,
24
23
    trace,
25
24
    tsort,
26
25
    )
 
26
from bzrlib.symbol_versioning import deprecated_function, deprecated_in
27
27
 
28
28
STEP_UNIQUE_SEARCHER_EVERY = 5
29
29
 
60
60
        return 'DictParentsProvider(%r)' % self.ancestry
61
61
 
62
62
    def get_parent_map(self, keys):
63
 
        """See _StackedParentsProvider.get_parent_map"""
 
63
        """See StackedParentsProvider.get_parent_map"""
64
64
        ancestry = self.ancestry
65
65
        return dict((k, ancestry[k]) for k in keys if k in ancestry)
66
66
 
67
 
 
68
 
class _StackedParentsProvider(object):
69
 
 
 
67
@deprecated_function(deprecated_in((1, 16, 0)))
 
68
def _StackedParentsProvider(*args, **kwargs):
 
69
    return StackedParentsProvider(*args, **kwargs)
 
70
 
 
71
class StackedParentsProvider(object):
 
72
    """A parents provider which stacks (or unions) multiple providers.
 
73
    
 
74
    The providers are queries in the order of the provided parent_providers.
 
75
    """
 
76
    
70
77
    def __init__(self, parent_providers):
71
78
        self._parent_providers = parent_providers
72
79
 
73
80
    def __repr__(self):
74
 
        return "_StackedParentsProvider(%r)" % self._parent_providers
 
81
        return "%s(%r)" % (self.__class__.__name__, self._parent_providers)
75
82
 
76
83
    def get_parent_map(self, keys):
77
84
        """Get a mapping of keys => parents
121
128
            self._get_parent_map = self._real_provider.get_parent_map
122
129
        else:
123
130
            self._get_parent_map = get_parent_map
124
 
        self._cache = {}
125
 
        self._cache_misses = True
 
131
        self._cache = None
 
132
        self.enable_cache(True)
126
133
 
127
134
    def __repr__(self):
128
135
        return "%s(%r)" % (self.__class__.__name__, self._real_provider)
133
140
            raise AssertionError('Cache enabled when already enabled.')
134
141
        self._cache = {}
135
142
        self._cache_misses = cache_misses
 
143
        self.missing_keys = set()
136
144
 
137
145
    def disable_cache(self):
138
146
        """Disable and clear the cache."""
139
147
        self._cache = None
 
148
        self._cache_misses = None
 
149
        self.missing_keys = set()
140
150
 
141
151
    def get_cached_map(self):
142
152
        """Return any cached get_parent_map values."""
143
153
        if self._cache is None:
144
154
            return None
145
 
        return dict((k, v) for k, v in self._cache.items()
146
 
                    if v is not None)
 
155
        return dict(self._cache)
147
156
 
148
157
    def get_parent_map(self, keys):
149
 
        """See _StackedParentsProvider.get_parent_map."""
150
 
        # Hack to build up the caching logic.
151
 
        ancestry = self._cache
152
 
        if ancestry is None:
153
 
            # Caching is disabled.
154
 
            missing_revisions = set(keys)
155
 
            ancestry = {}
 
158
        """See StackedParentsProvider.get_parent_map."""
 
159
        cache = self._cache
 
160
        if cache is None:
 
161
            cache = self._get_parent_map(keys)
156
162
        else:
157
 
            missing_revisions = set(key for key in keys if key not in ancestry)
158
 
        if missing_revisions:
159
 
            parent_map = self._get_parent_map(missing_revisions)
160
 
            ancestry.update(parent_map)
161
 
            if self._cache_misses:
162
 
                # None is never a valid parents list, so it can be used to
163
 
                # record misses.
164
 
                ancestry.update(dict((k, None) for k in missing_revisions
165
 
                                     if k not in parent_map))
166
 
        present_keys = [k for k in keys if ancestry.get(k) is not None]
167
 
        return dict((k, ancestry[k]) for k in present_keys)
 
163
            needed_revisions = set(key for key in keys if key not in cache)
 
164
            # Do not ask for negatively cached keys
 
165
            needed_revisions.difference_update(self.missing_keys)
 
166
            if needed_revisions:
 
167
                parent_map = self._get_parent_map(needed_revisions)
 
168
                cache.update(parent_map)
 
169
                if self._cache_misses:
 
170
                    for key in needed_revisions:
 
171
                        if key not in parent_map:
 
172
                            self.note_missing_key(key)
 
173
        result = {}
 
174
        for key in keys:
 
175
            value = cache.get(key)
 
176
            if value is not None:
 
177
                result[key] = value
 
178
        return result
 
179
 
 
180
    def note_missing_key(self, key):
 
181
        """Note that key is a missing key."""
 
182
        if self._cache_misses:
 
183
            self.missing_keys.add(key)
168
184
 
169
185
 
170
186
class Graph(object):
551
567
    def _refine_unique_nodes(self, unique_searcher, all_unique_searcher,
552
568
                             unique_tip_searchers, common_searcher):
553
569
        """Steps 5-8 of find_unique_ancestors.
554
 
        
 
570
 
555
571
        This function returns when common_searcher has stopped searching for
556
572
        more nodes.
557
573
        """
600
616
                                 all_unique_searcher._iterations)
601
617
            unique_tip_searchers = next_unique_searchers
602
618
 
603
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
604
 
    def get_parents(self, revisions):
605
 
        """Find revision ids of the parents of a list of revisions
606
 
 
607
 
        A list is returned of the same length as the input.  Each entry
608
 
        is a list of parent ids for the corresponding input revision.
609
 
 
610
 
        [NULL_REVISION] is used as the parent of the first user-committed
611
 
        revision.  Its parent list is empty.
612
 
 
613
 
        If the revision is not present (i.e. a ghost), None is used in place
614
 
        of the list of parents.
615
 
 
616
 
        Deprecated in bzr 1.2 - please see get_parent_map.
617
 
        """
618
 
        parents = self.get_parent_map(revisions)
619
 
        return [parents.get(r, None) for r in revisions]
620
 
 
621
619
    def get_parent_map(self, revisions):
622
620
        """Get a map of key:parent_list for revisions.
623
621
 
1209
1207
 
1210
1208
    def get_result(self):
1211
1209
        """Get a SearchResult for the current state of this searcher.
1212
 
        
 
1210
 
1213
1211
        :return: A SearchResult for this search so far. The SearchResult is
1214
1212
            static - the search can be advanced and the search result will not
1215
1213
            be invalidated or altered.
1219
1217
            # exclude keys for them. However, while we could have a second
1220
1218
            # look-ahead result buffer and shuffle things around, this method
1221
1219
            # is typically only called once per search - when memoising the
1222
 
            # results of the search. 
 
1220
            # results of the search.
1223
1221
            found, ghosts, next, parents = self._do_query(self._next_query)
1224
1222
            # pretend we didn't query: perhaps we should tweak _do_query to be
1225
1223
            # entirely stateless?
1266
1264
 
1267
1265
    def next_with_ghosts(self):
1268
1266
        """Return the next found ancestors, with ghosts split out.
1269
 
        
 
1267
 
1270
1268
        Ancestors are returned in the order they are seen in a breadth-first
1271
1269
        traversal.  No ancestor will be returned more than once. Ancestors are
1272
1270
        returned only after asking for their parents, which allows us to detect
1331
1329
 
1332
1330
    def find_seen_ancestors(self, revisions):
1333
1331
        """Find ancestors of these revisions that have already been seen.
1334
 
        
 
1332
 
1335
1333
        This function generally makes the assumption that querying for the
1336
1334
        parents of a node that has already been queried is reasonably cheap.
1337
1335
        (eg, not a round trip to a remote host).
1393
1391
                self._current_ghosts.intersection(revisions))
1394
1392
            self._current_present.difference_update(stopped)
1395
1393
            self._current_ghosts.difference_update(stopped)
1396
 
            # stopping 'x' should stop returning parents of 'x', but 
 
1394
            # stopping 'x' should stop returning parents of 'x', but
1397
1395
            # not if 'y' always references those same parents
1398
1396
            stop_rev_references = {}
1399
1397
            for rev in stopped_present:
1415
1413
                    stop_parents.add(rev_id)
1416
1414
            self._next_query.difference_update(stop_parents)
1417
1415
        self._stopped_keys.update(stopped)
1418
 
        self._stopped_keys.update(revisions - set([revision.NULL_REVISION]))
 
1416
        self._stopped_keys.update(revisions)
1419
1417
        return stopped
1420
1418
 
1421
1419
    def start_searching(self, revisions):
1461
1459
            a SearchResult from a smart server, in which case the keys list is
1462
1460
            not necessarily immediately available.
1463
1461
        """
1464
 
        self._recipe = (start_keys, exclude_keys, key_count)
 
1462
        self._recipe = ('search', start_keys, exclude_keys, key_count)
1465
1463
        self._keys = frozenset(keys)
1466
1464
 
1467
1465
    def get_recipe(self):
1468
1466
        """Return a recipe that can be used to replay this search.
1469
 
        
 
1467
 
1470
1468
        The recipe allows reconstruction of the same results at a later date
1471
1469
        without knowing all the found keys. The essential elements are a list
1472
 
        of keys to start and and to stop at. In order to give reproducible
 
1470
        of keys to start and to stop at. In order to give reproducible
1473
1471
        results when ghosts are encountered by a search they are automatically
1474
1472
        added to the exclude list (or else ghost filling may alter the
1475
1473
        results).
1476
1474
 
1477
 
        :return: A tuple (start_keys_set, exclude_keys_set, revision_count). To
1478
 
            recreate the results of this search, create a breadth first
1479
 
            searcher on the same graph starting at start_keys. Then call next()
1480
 
            (or next_with_ghosts()) repeatedly, and on every result, call
1481
 
            stop_searching_any on any keys from the exclude_keys set. The
1482
 
            revision_count value acts as a trivial cross-check - the found
1483
 
            revisions of the new search should have as many elements as
 
1475
        :return: A tuple ('search', start_keys_set, exclude_keys_set,
 
1476
            revision_count). To recreate the results of this search, create a
 
1477
            breadth first searcher on the same graph starting at start_keys.
 
1478
            Then call next() (or next_with_ghosts()) repeatedly, and on every
 
1479
            result, call stop_searching_any on any keys from the exclude_keys
 
1480
            set. The revision_count value acts as a trivial cross-check - the
 
1481
            found revisions of the new search should have as many elements as
1484
1482
            revision_count. If it does not, then additional revisions have been
1485
1483
            ghosted since the search was executed the first time and the second
1486
1484
            time.
1494
1492
        """
1495
1493
        return self._keys
1496
1494
 
 
1495
    def is_empty(self):
 
1496
        """Return false if the search lists 1 or more revisions."""
 
1497
        return self._recipe[3] == 0
 
1498
 
 
1499
    def refine(self, seen, referenced):
 
1500
        """Create a new search by refining this search.
 
1501
 
 
1502
        :param seen: Revisions that have been satisfied.
 
1503
        :param referenced: Revision references observed while satisfying some
 
1504
            of this search.
 
1505
        """
 
1506
        start = self._recipe[1]
 
1507
        exclude = self._recipe[2]
 
1508
        count = self._recipe[3]
 
1509
        keys = self.get_keys()
 
1510
        # New heads = referenced + old heads - seen things - exclude
 
1511
        pending_refs = set(referenced)
 
1512
        pending_refs.update(start)
 
1513
        pending_refs.difference_update(seen)
 
1514
        pending_refs.difference_update(exclude)
 
1515
        # New exclude = old exclude + satisfied heads
 
1516
        seen_heads = start.intersection(seen)
 
1517
        exclude.update(seen_heads)
 
1518
        # keys gets seen removed
 
1519
        keys = keys - seen
 
1520
        # length is reduced by len(seen)
 
1521
        count -= len(seen)
 
1522
        return SearchResult(pending_refs, exclude, count, keys)
 
1523
 
 
1524
 
 
1525
class PendingAncestryResult(object):
 
1526
    """A search result that will reconstruct the ancestry for some graph heads.
 
1527
 
 
1528
    Unlike SearchResult, this doesn't hold the complete search result in
 
1529
    memory, it just holds a description of how to generate it.
 
1530
    """
 
1531
 
 
1532
    def __init__(self, heads, repo):
 
1533
        """Constructor.
 
1534
 
 
1535
        :param heads: an iterable of graph heads.
 
1536
        :param repo: a repository to use to generate the ancestry for the given
 
1537
            heads.
 
1538
        """
 
1539
        self.heads = frozenset(heads)
 
1540
        self.repo = repo
 
1541
 
 
1542
    def get_recipe(self):
 
1543
        """Return a recipe that can be used to replay this search.
 
1544
 
 
1545
        The recipe allows reconstruction of the same results at a later date.
 
1546
 
 
1547
        :seealso SearchResult.get_recipe:
 
1548
 
 
1549
        :return: A tuple ('proxy-search', start_keys_set, set(), -1)
 
1550
            To recreate this result, create a PendingAncestryResult with the
 
1551
            start_keys_set.
 
1552
        """
 
1553
        return ('proxy-search', self.heads, set(), -1)
 
1554
 
 
1555
    def get_keys(self):
 
1556
        """See SearchResult.get_keys.
 
1557
 
 
1558
        Returns all the keys for the ancestry of the heads, excluding
 
1559
        NULL_REVISION.
 
1560
        """
 
1561
        return self._get_keys(self.repo.get_graph())
 
1562
 
 
1563
    def _get_keys(self, graph):
 
1564
        NULL_REVISION = revision.NULL_REVISION
 
1565
        keys = [key for (key, parents) in graph.iter_ancestry(self.heads)
 
1566
                if key != NULL_REVISION and parents is not None]
 
1567
        return keys
 
1568
 
 
1569
    def is_empty(self):
 
1570
        """Return false if the search lists 1 or more revisions."""
 
1571
        if revision.NULL_REVISION in self.heads:
 
1572
            return len(self.heads) == 1
 
1573
        else:
 
1574
            return len(self.heads) == 0
 
1575
 
 
1576
    def refine(self, seen, referenced):
 
1577
        """Create a new search by refining this search.
 
1578
 
 
1579
        :param seen: Revisions that have been satisfied.
 
1580
        :param referenced: Revision references observed while satisfying some
 
1581
            of this search.
 
1582
        """
 
1583
        referenced = self.heads.union(referenced)
 
1584
        return PendingAncestryResult(referenced - seen, self.repo)
 
1585
 
1497
1586
 
1498
1587
def collapse_linear_regions(parent_map):
1499
1588
    """Collapse regions of the graph that are 'linear'.
1566
1655
            removed.add(node)
1567
1656
 
1568
1657
    return result
 
1658
 
 
1659
 
 
1660
_counters = [0,0,0,0,0,0,0]
 
1661
try:
 
1662
    from bzrlib._known_graph_pyx import KnownGraph
 
1663
except ImportError:
 
1664
    from bzrlib._known_graph_py import KnownGraph