~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/graph.py

(vila) Revise legal option names to be less drastic. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
 
18
 
17
19
import time
18
20
 
19
21
from bzrlib import (
23
25
    revision,
24
26
    trace,
25
27
    )
26
 
from bzrlib.symbol_versioning import deprecated_function, deprecated_in
27
28
 
28
29
STEP_UNIQUE_SEARCHER_EVERY = 5
29
30
 
59
60
    def __repr__(self):
60
61
        return 'DictParentsProvider(%r)' % self.ancestry
61
62
 
 
63
    # Note: DictParentsProvider does not implement get_cached_parent_map
 
64
    #       Arguably, the data is clearly cached in memory. However, this class
 
65
    #       is mostly used for testing, and it keeps the tests clean to not
 
66
    #       change it.
 
67
 
62
68
    def get_parent_map(self, keys):
63
69
        """See StackedParentsProvider.get_parent_map"""
64
70
        ancestry = self.ancestry
65
 
        return dict((k, ancestry[k]) for k in keys if k in ancestry)
 
71
        return dict([(k, ancestry[k]) for k in keys if k in ancestry])
66
72
 
67
73
 
68
74
class StackedParentsProvider(object):
69
75
    """A parents provider which stacks (or unions) multiple providers.
70
 
    
 
76
 
71
77
    The providers are queries in the order of the provided parent_providers.
72
78
    """
73
 
    
 
79
 
74
80
    def __init__(self, parent_providers):
75
81
        self._parent_providers = parent_providers
76
82
 
92
98
        """
93
99
        found = {}
94
100
        remaining = set(keys)
 
101
        # This adds getattr() overhead to each get_parent_map call. However,
 
102
        # this is StackedParentsProvider, which means we're dealing with I/O
 
103
        # (either local indexes, or remote RPCs), so CPU overhead should be
 
104
        # minimal.
 
105
        for parents_provider in self._parent_providers:
 
106
            get_cached = getattr(parents_provider, 'get_cached_parent_map',
 
107
                                 None)
 
108
            if get_cached is None:
 
109
                continue
 
110
            new_found = get_cached(remaining)
 
111
            found.update(new_found)
 
112
            remaining.difference_update(new_found)
 
113
            if not remaining:
 
114
                break
 
115
        if not remaining:
 
116
            return found
95
117
        for parents_provider in self._parent_providers:
96
118
            new_found = parents_provider.get_parent_map(remaining)
97
119
            found.update(new_found)
151
173
            return None
152
174
        return dict(self._cache)
153
175
 
 
176
    def get_cached_parent_map(self, keys):
 
177
        """Return items from the cache.
 
178
 
 
179
        This returns the same info as get_parent_map, but explicitly does not
 
180
        invoke the supplied ParentsProvider to search for uncached values.
 
181
        """
 
182
        cache = self._cache
 
183
        if cache is None:
 
184
            return {}
 
185
        return dict([(key, cache[key]) for key in keys if key in cache])
 
186
 
154
187
    def get_parent_map(self, keys):
155
188
        """See StackedParentsProvider.get_parent_map."""
156
189
        cache = self._cache
180
213
            self.missing_keys.add(key)
181
214
 
182
215
 
 
216
class CallableToParentsProviderAdapter(object):
 
217
    """A parents provider that adapts any callable to the parents provider API.
 
218
 
 
219
    i.e. it accepts calls to self.get_parent_map and relays them to the
 
220
    callable it was constructed with.
 
221
    """
 
222
 
 
223
    def __init__(self, a_callable):
 
224
        self.callable = a_callable
 
225
 
 
226
    def __repr__(self):
 
227
        return "%s(%r)" % (self.__class__.__name__, self.callable)
 
228
 
 
229
    def get_parent_map(self, keys):
 
230
        return self.callable(keys)
 
231
 
 
232
 
183
233
class Graph(object):
184
234
    """Provide incremental access to revision graphs.
185
235
 
234
284
        common ancestor of all border ancestors, because this shows that it
235
285
        cannot be a descendant of any border ancestor.
236
286
 
237
 
        The scaling of this operation should be proportional to
 
287
        The scaling of this operation should be proportional to:
 
288
 
238
289
        1. The number of uncommon ancestors
239
290
        2. The number of border ancestors
240
291
        3. The length of the shortest path between a border ancestor and an
372
423
 
373
424
        :param unique_revision: The revision_id whose ancestry we are
374
425
            interested in.
375
 
            XXX: Would this API be better if we allowed multiple revisions on
376
 
                 to be searched here?
 
426
            (XXX: Would this API be better if we allowed multiple revisions on
 
427
            to be searched here?)
377
428
        :param common_revisions: Revision_ids of ancestries to exclude.
378
429
        :return: A set of revisions in the ancestry of unique_revision
379
430
        """
1297
1348
        return ('_BreadthFirstSearcher(iterations=%d, %s,'
1298
1349
                ' seen=%r)' % (self._iterations, search, list(self.seen)))
1299
1350
 
1300
 
    def get_result(self):
1301
 
        """Get a SearchResult for the current state of this searcher.
 
1351
    def get_state(self):
 
1352
        """Get the current state of this searcher.
1302
1353
 
1303
 
        :return: A SearchResult for this search so far. The SearchResult is
1304
 
            static - the search can be advanced and the search result will not
1305
 
            be invalidated or altered.
 
1354
        :return: Tuple with started keys, excludes and included keys
1306
1355
        """
1307
1356
        if self._returning == 'next':
1308
1357
            # We have to know the current nodes children to be able to list the
1319
1368
            next_query = self._next_query
1320
1369
        excludes = self._stopped_keys.union(next_query)
1321
1370
        included_keys = self.seen.difference(excludes)
1322
 
        return SearchResult(self._started_keys, excludes, len(included_keys),
 
1371
        return self._started_keys, excludes, included_keys
 
1372
 
 
1373
    def _get_result(self):
 
1374
        """Get a SearchResult for the current state of this searcher.
 
1375
 
 
1376
        :return: A SearchResult for this search so far. The SearchResult is
 
1377
            static - the search can be advanced and the search result will not
 
1378
            be invalidated or altered.
 
1379
        """
 
1380
        from bzrlib.vf_search import SearchResult
 
1381
        (started_keys, excludes, included_keys) = self.get_state()
 
1382
        return SearchResult(started_keys, excludes, len(included_keys),
1323
1383
            included_keys)
1324
1384
 
1325
1385
    def step(self):
1402
1462
        parents_of_found = set()
1403
1463
        # revisions may contain nodes that point to other nodes in revisions:
1404
1464
        # we want to filter them out.
1405
 
        self.seen.update(revisions)
 
1465
        seen = self.seen
 
1466
        seen.update(revisions)
1406
1467
        parent_map = self._parents_provider.get_parent_map(revisions)
1407
1468
        found_revisions.update(parent_map)
1408
1469
        for rev_id, parents in parent_map.iteritems():
1409
1470
            if parents is None:
1410
1471
                continue
1411
 
            new_found_parents = [p for p in parents if p not in self.seen]
 
1472
            new_found_parents = [p for p in parents if p not in seen]
1412
1473
            if new_found_parents:
1413
1474
                # Calling set.update() with an empty generator is actually
1414
1475
                # rather expensive.
1533
1594
            return revs, ghosts
1534
1595
 
1535
1596
 
1536
 
class AbstractSearchResult(object):
1537
 
    """The result of a search, describing a set of keys.
1538
 
    
1539
 
    Search results are typically used as the 'fetch_spec' parameter when
1540
 
    fetching revisions.
1541
 
 
1542
 
    :seealso: AbstractSearch
1543
 
    """
1544
 
 
1545
 
    def get_recipe(self):
1546
 
        """Return a recipe that can be used to replay this search.
1547
 
 
1548
 
        The recipe allows reconstruction of the same results at a later date.
1549
 
 
1550
 
        :return: A tuple of (search_kind_str, *details).  The details vary by
1551
 
            kind of search result.
1552
 
        """
1553
 
        raise NotImplementedError(self.get_recipe)
1554
 
 
1555
 
    def get_network_struct(self):
1556
 
        """Return a tuple that can be transmitted via the HPSS protocol."""
1557
 
        raise NotImplementedError(self.get_network_struct)
1558
 
 
1559
 
    def get_keys(self):
1560
 
        """Return the keys found in this search.
1561
 
 
1562
 
        :return: A set of keys.
1563
 
        """
1564
 
        raise NotImplementedError(self.get_keys)
1565
 
 
1566
 
    def is_empty(self):
1567
 
        """Return false if the search lists 1 or more revisions."""
1568
 
        raise NotImplementedError(self.is_empty)
1569
 
 
1570
 
    def refine(self, seen, referenced):
1571
 
        """Create a new search by refining this search.
1572
 
 
1573
 
        :param seen: Revisions that have been satisfied.
1574
 
        :param referenced: Revision references observed while satisfying some
1575
 
            of this search.
1576
 
        :return: A search result.
1577
 
        """
1578
 
        raise NotImplementedError(self.refine)
1579
 
 
1580
 
 
1581
 
class AbstractSearch(object):
1582
 
    """A search that can be executed, producing a search result.
1583
 
 
1584
 
    :seealso: AbstractSearchResult
1585
 
    """
1586
 
 
1587
 
    def execute(self):
1588
 
        """Construct a network-ready search result from this search description.
1589
 
 
1590
 
        This may take some time to search repositories, etc.
1591
 
 
1592
 
        :return: A search result (an object that implements
1593
 
            AbstractSearchResult's API).
1594
 
        """
1595
 
        raise NotImplementedError(self.execute)
1596
 
 
1597
 
 
1598
 
class SearchResult(AbstractSearchResult):
1599
 
    """The result of a breadth first search.
1600
 
 
1601
 
    A SearchResult provides the ability to reconstruct the search or access a
1602
 
    set of the keys the search found.
1603
 
    """
1604
 
 
1605
 
    def __init__(self, start_keys, exclude_keys, key_count, keys):
1606
 
        """Create a SearchResult.
1607
 
 
1608
 
        :param start_keys: The keys the search started at.
1609
 
        :param exclude_keys: The keys the search excludes.
1610
 
        :param key_count: The total number of keys (from start to but not
1611
 
            including exclude).
1612
 
        :param keys: The keys the search found. Note that in future we may get
1613
 
            a SearchResult from a smart server, in which case the keys list is
1614
 
            not necessarily immediately available.
1615
 
        """
1616
 
        self._recipe = ('search', start_keys, exclude_keys, key_count)
1617
 
        self._keys = frozenset(keys)
1618
 
 
1619
 
    def __repr__(self):
1620
 
        kind, start_keys, exclude_keys, key_count = self._recipe
1621
 
        if len(start_keys) > 5:
1622
 
            start_keys_repr = repr(list(start_keys)[:5])[:-1] + ', ...]'
1623
 
        else:
1624
 
            start_keys_repr = repr(start_keys)
1625
 
        if len(exclude_keys) > 5:
1626
 
            exclude_keys_repr = repr(list(exclude_keys)[:5])[:-1] + ', ...]'
1627
 
        else:
1628
 
            exclude_keys_repr = repr(exclude_keys)
1629
 
        return '<%s %s:(%s, %s, %d)>' % (self.__class__.__name__,
1630
 
            kind, start_keys_repr, exclude_keys_repr, key_count)
1631
 
 
1632
 
    def get_recipe(self):
1633
 
        """Return a recipe that can be used to replay this search.
1634
 
 
1635
 
        The recipe allows reconstruction of the same results at a later date
1636
 
        without knowing all the found keys. The essential elements are a list
1637
 
        of keys to start and to stop at. In order to give reproducible
1638
 
        results when ghosts are encountered by a search they are automatically
1639
 
        added to the exclude list (or else ghost filling may alter the
1640
 
        results).
1641
 
 
1642
 
        :return: A tuple ('search', start_keys_set, exclude_keys_set,
1643
 
            revision_count). To recreate the results of this search, create a
1644
 
            breadth first searcher on the same graph starting at start_keys.
1645
 
            Then call next() (or next_with_ghosts()) repeatedly, and on every
1646
 
            result, call stop_searching_any on any keys from the exclude_keys
1647
 
            set. The revision_count value acts as a trivial cross-check - the
1648
 
            found revisions of the new search should have as many elements as
1649
 
            revision_count. If it does not, then additional revisions have been
1650
 
            ghosted since the search was executed the first time and the second
1651
 
            time.
1652
 
        """
1653
 
        return self._recipe
1654
 
 
1655
 
    def get_network_struct(self):
1656
 
        start_keys = ' '.join(self._recipe[1])
1657
 
        stop_keys = ' '.join(self._recipe[2])
1658
 
        count = str(self._recipe[3])
1659
 
        return (self._recipe[0], '\n'.join((start_keys, stop_keys, count)))
1660
 
 
1661
 
    def get_keys(self):
1662
 
        """Return the keys found in this search.
1663
 
 
1664
 
        :return: A set of keys.
1665
 
        """
1666
 
        return self._keys
1667
 
 
1668
 
    def is_empty(self):
1669
 
        """Return false if the search lists 1 or more revisions."""
1670
 
        return self._recipe[3] == 0
1671
 
 
1672
 
    def refine(self, seen, referenced):
1673
 
        """Create a new search by refining this search.
1674
 
 
1675
 
        :param seen: Revisions that have been satisfied.
1676
 
        :param referenced: Revision references observed while satisfying some
1677
 
            of this search.
1678
 
        """
1679
 
        start = self._recipe[1]
1680
 
        exclude = self._recipe[2]
1681
 
        count = self._recipe[3]
1682
 
        keys = self.get_keys()
1683
 
        # New heads = referenced + old heads - seen things - exclude
1684
 
        pending_refs = set(referenced)
1685
 
        pending_refs.update(start)
1686
 
        pending_refs.difference_update(seen)
1687
 
        pending_refs.difference_update(exclude)
1688
 
        # New exclude = old exclude + satisfied heads
1689
 
        seen_heads = start.intersection(seen)
1690
 
        exclude.update(seen_heads)
1691
 
        # keys gets seen removed
1692
 
        keys = keys - seen
1693
 
        # length is reduced by len(seen)
1694
 
        count -= len(seen)
1695
 
        return SearchResult(pending_refs, exclude, count, keys)
1696
 
 
1697
 
 
1698
 
class PendingAncestryResult(AbstractSearchResult):
1699
 
    """A search result that will reconstruct the ancestry for some graph heads.
1700
 
 
1701
 
    Unlike SearchResult, this doesn't hold the complete search result in
1702
 
    memory, it just holds a description of how to generate it.
1703
 
    """
1704
 
 
1705
 
    def __init__(self, heads, repo):
1706
 
        """Constructor.
1707
 
 
1708
 
        :param heads: an iterable of graph heads.
1709
 
        :param repo: a repository to use to generate the ancestry for the given
1710
 
            heads.
1711
 
        """
1712
 
        self.heads = frozenset(heads)
1713
 
        self.repo = repo
1714
 
 
1715
 
    def __repr__(self):
1716
 
        if len(self.heads) > 5:
1717
 
            heads_repr = repr(list(self.heads)[:5])[:-1]
1718
 
            heads_repr += ', <%d more>...]' % (len(self.heads) - 5,)
1719
 
        else:
1720
 
            heads_repr = repr(self.heads)
1721
 
        return '<%s heads:%s repo:%r>' % (
1722
 
            self.__class__.__name__, heads_repr, self.repo)
1723
 
 
1724
 
    def get_recipe(self):
1725
 
        """Return a recipe that can be used to replay this search.
1726
 
 
1727
 
        The recipe allows reconstruction of the same results at a later date.
1728
 
 
1729
 
        :seealso SearchResult.get_recipe:
1730
 
 
1731
 
        :return: A tuple ('proxy-search', start_keys_set, set(), -1)
1732
 
            To recreate this result, create a PendingAncestryResult with the
1733
 
            start_keys_set.
1734
 
        """
1735
 
        return ('proxy-search', self.heads, set(), -1)
1736
 
 
1737
 
    def get_network_struct(self):
1738
 
        parts = ['ancestry-of']
1739
 
        parts.extend(self.heads)
1740
 
        return parts
1741
 
 
1742
 
    def get_keys(self):
1743
 
        """See SearchResult.get_keys.
1744
 
 
1745
 
        Returns all the keys for the ancestry of the heads, excluding
1746
 
        NULL_REVISION.
1747
 
        """
1748
 
        return self._get_keys(self.repo.get_graph())
1749
 
 
1750
 
    def _get_keys(self, graph):
1751
 
        NULL_REVISION = revision.NULL_REVISION
1752
 
        keys = [key for (key, parents) in graph.iter_ancestry(self.heads)
1753
 
                if key != NULL_REVISION and parents is not None]
1754
 
        return keys
1755
 
 
1756
 
    def is_empty(self):
1757
 
        """Return false if the search lists 1 or more revisions."""
1758
 
        if revision.NULL_REVISION in self.heads:
1759
 
            return len(self.heads) == 1
1760
 
        else:
1761
 
            return len(self.heads) == 0
1762
 
 
1763
 
    def refine(self, seen, referenced):
1764
 
        """Create a new search by refining this search.
1765
 
 
1766
 
        :param seen: Revisions that have been satisfied.
1767
 
        :param referenced: Revision references observed while satisfying some
1768
 
            of this search.
1769
 
        """
1770
 
        referenced = self.heads.union(referenced)
1771
 
        return PendingAncestryResult(referenced - seen, self.repo)
1772
 
 
1773
 
 
1774
 
class EmptySearchResult(AbstractSearchResult):
1775
 
    """An empty search result."""
1776
 
 
1777
 
    def is_empty(self):
1778
 
        return True
1779
 
    
1780
 
 
1781
 
class EverythingResult(AbstractSearchResult):
1782
 
    """A search result that simply requests everything in the repository."""
1783
 
 
1784
 
    def __init__(self, repo):
1785
 
        self._repo = repo
1786
 
 
1787
 
    def __repr__(self):
1788
 
        return '%s(%r)' % (self.__class__.__name__, self._repo)
1789
 
 
1790
 
    def get_recipe(self):
1791
 
        raise NotImplementedError(self.get_recipe)
1792
 
 
1793
 
    def get_network_struct(self):
1794
 
        return ('everything',)
1795
 
 
1796
 
    def get_keys(self):
1797
 
        if 'evil' in debug.debug_flags:
1798
 
            from bzrlib import remote
1799
 
            if isinstance(self._repo, remote.RemoteRepository):
1800
 
                # warn developers (not users) not to do this
1801
 
                trace.mutter_callsite(
1802
 
                    2, "EverythingResult(RemoteRepository).get_keys() is slow.")
1803
 
        return self._repo.all_revision_ids()
1804
 
 
1805
 
    def is_empty(self):
1806
 
        # It's ok for this to wrongly return False: the worst that can happen
1807
 
        # is that RemoteStreamSource will initiate a get_stream on an empty
1808
 
        # repository.  And almost all repositories are non-empty.
1809
 
        return False
1810
 
 
1811
 
    def refine(self, seen, referenced):
1812
 
        heads = set(self._repo.all_revision_ids())
1813
 
        heads.difference_update(seen)
1814
 
        heads.update(referenced)
1815
 
        return PendingAncestryResult(heads, self._repo)
1816
 
 
1817
 
 
1818
 
class EverythingNotInOther(AbstractSearch):
1819
 
    """Find all revisions in that are in one repo but not the other."""
1820
 
 
1821
 
    def __init__(self, to_repo, from_repo, find_ghosts=False):
1822
 
        self.to_repo = to_repo
1823
 
        self.from_repo = from_repo
1824
 
        self.find_ghosts = find_ghosts
1825
 
 
1826
 
    def execute(self):
1827
 
        return self.to_repo.search_missing_revision_ids(
1828
 
            self.from_repo, find_ghosts=self.find_ghosts)
1829
 
 
1830
 
 
1831
 
class NotInOtherForRevs(AbstractSearch):
1832
 
    """Find all revisions missing in one repo for a some specific heads."""
1833
 
 
1834
 
    def __init__(self, to_repo, from_repo, required_ids, if_present_ids=None,
1835
 
            find_ghosts=False):
1836
 
        """Constructor.
1837
 
 
1838
 
        :param required_ids: revision IDs of heads that must be found, or else
1839
 
            the search will fail with NoSuchRevision.  All revisions in their
1840
 
            ancestry not already in the other repository will be included in
1841
 
            the search result.
1842
 
        :param if_present_ids: revision IDs of heads that may be absent in the
1843
 
            source repository.  If present, then their ancestry not already
1844
 
            found in other will be included in the search result.
1845
 
        """
1846
 
        self.to_repo = to_repo
1847
 
        self.from_repo = from_repo
1848
 
        self.find_ghosts = find_ghosts
1849
 
        self.required_ids = required_ids
1850
 
        self.if_present_ids = if_present_ids
1851
 
 
1852
 
    def __repr__(self):
1853
 
        if len(self.required_ids) > 5:
1854
 
            reqd_revs_repr = repr(list(self.required_ids)[:5])[:-1] + ', ...]'
1855
 
        else:
1856
 
            reqd_revs_repr = repr(self.required_ids)
1857
 
        if self.if_present_ids and len(self.if_present_ids) > 5:
1858
 
            ifp_revs_repr = repr(list(self.if_present_ids)[:5])[:-1] + ', ...]'
1859
 
        else:
1860
 
            ifp_revs_repr = repr(self.if_present_ids)
1861
 
 
1862
 
        return "<%s from:%r to:%r find_ghosts:%r req'd:%r if-present:%r>" % (
1863
 
            self.__class__.__name__, self.from_repo, self.to_repo,
1864
 
            self.find_ghosts, reqd_revs_repr, ifp_revs_repr)
1865
 
 
1866
 
    def execute(self):
1867
 
        return self.to_repo.search_missing_revision_ids(
1868
 
            self.from_repo, revision_ids=self.required_ids,
1869
 
            if_present_ids=self.if_present_ids, find_ghosts=self.find_ghosts)
 
1597
def invert_parent_map(parent_map):
 
1598
    """Given a map from child => parents, create a map of parent=>children"""
 
1599
    child_map = {}
 
1600
    for child, parents in parent_map.iteritems():
 
1601
        for p in parents:
 
1602
            # Any given parent is likely to have only a small handful
 
1603
            # of children, many will have only one. So we avoid mem overhead of
 
1604
            # a list, in exchange for extra copying of tuples
 
1605
            if p not in child_map:
 
1606
                child_map[p] = (child,)
 
1607
            else:
 
1608
                child_map[p] = child_map[p] + (child,)
 
1609
    return child_map
1870
1610
 
1871
1611
 
1872
1612
def collapse_linear_regions(parent_map):
1958
1698
        return set([h[0] for h in head_keys])
1959
1699
 
1960
1700
    def merge_sort(self, tip_revision):
1961
 
        return self._graph.merge_sort((tip_revision,))
 
1701
        nodes = self._graph.merge_sort((tip_revision,))
 
1702
        for node in nodes:
 
1703
            node.key = node.key[0]
 
1704
        return nodes
1962
1705
 
1963
1706
    def add_node(self, revision, parents):
1964
1707
        self._graph.add_node((revision,), [(p,) for p in parents])