/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/revision.py

  • Committer: John Arbash Meinel
  • Date: 2006-05-27 03:11:07 UTC
  • mto: (1711.2.26 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1734.
  • Revision ID: john@arbash-meinel.com-20060527031107-6969266aa397354e
Adding a benchmark which checks 'bzr status' time after a commit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# (C) 2005 Canonical
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
# TODO: Some kind of command-line display of revision properties: 
 
18
# perhaps show them in log -v and allow them as options to the commit command.
 
19
 
 
20
 
 
21
import bzrlib.errors
 
22
import bzrlib.errors as errors
 
23
from bzrlib.graph import node_distances, select_farthest, all_descendants, Graph
 
24
from bzrlib.osutils import contains_whitespace
 
25
from bzrlib.progress import DummyProgress
 
26
from bzrlib.symbol_versioning import *
 
27
 
 
28
 
 
29
NULL_REVISION="null:"
 
30
 
 
31
 
 
32
class Revision(object):
 
33
    """Single revision on a branch.
 
34
 
 
35
    Revisions may know their revision_hash, but only once they've been
 
36
    written out.  This is not stored because you cannot write the hash
 
37
    into the file it describes.
 
38
 
 
39
    After bzr 0.0.5 revisions are allowed to have multiple parents.
 
40
 
 
41
    parent_ids
 
42
        List of parent revision_ids
 
43
 
 
44
    properties
 
45
        Dictionary of revision properties.  These are attached to the
 
46
        revision as extra metadata.  The name must be a single 
 
47
        word; the value can be an arbitrary string.
 
48
    """
 
49
    
 
50
    def __init__(self, revision_id, properties=None, **args):
 
51
        self.revision_id = revision_id
 
52
        self.properties = properties or {}
 
53
        self._check_properties()
 
54
        self.parent_ids = []
 
55
        self.parent_sha1s = []
 
56
        self.__dict__.update(args)
 
57
 
 
58
    def __repr__(self):
 
59
        return "<Revision id %s>" % self.revision_id
 
60
 
 
61
    def __eq__(self, other):
 
62
        if not isinstance(other, Revision):
 
63
            return False
 
64
        # FIXME: rbc 20050930 parent_ids are not being compared
 
65
        return (
 
66
                self.inventory_sha1 == other.inventory_sha1
 
67
                and self.revision_id == other.revision_id
 
68
                and self.timestamp == other.timestamp
 
69
                and self.message == other.message
 
70
                and self.timezone == other.timezone
 
71
                and self.committer == other.committer
 
72
                and self.properties == other.properties)
 
73
 
 
74
    def __ne__(self, other):
 
75
        return not self.__eq__(other)
 
76
 
 
77
    def _check_properties(self):
 
78
        """Verify that all revision properties are OK.
 
79
        """
 
80
        for name, value in self.properties.iteritems():
 
81
            if not isinstance(name, basestring) or contains_whitespace(name):
 
82
                raise ValueError("invalid property name %r" % name)
 
83
            if not isinstance(value, basestring):
 
84
                raise ValueError("invalid property value %r for %r" % 
 
85
                                 (name, value))
 
86
 
 
87
    def get_history(self, repository):
 
88
        """Return the canonical line-of-history for this revision.
 
89
 
 
90
        If ghosts are present this may differ in result from a ghost-free
 
91
        repository.
 
92
        """
 
93
        current_revision = self
 
94
        reversed_result = []
 
95
        while current_revision is not None:
 
96
            reversed_result.append(current_revision.revision_id)
 
97
            if not len (current_revision.parent_ids):
 
98
                reversed_result.append(None)
 
99
                current_revision = None
 
100
            else:
 
101
                next_revision_id = current_revision.parent_ids[0]
 
102
                current_revision = repository.get_revision(next_revision_id)
 
103
        reversed_result.reverse()
 
104
        return reversed_result
 
105
 
 
106
 
 
107
def is_ancestor(revision_id, candidate_id, branch):
 
108
    """Return true if candidate_id is an ancestor of revision_id.
 
109
 
 
110
    A false negative will be returned if any intermediate descendent of
 
111
    candidate_id is not present in any of the revision_sources.
 
112
    
 
113
    revisions_source is an object supporting a get_revision operation that
 
114
    behaves like Branch's.
 
115
    """
 
116
    return candidate_id in branch.repository.get_ancestry(revision_id)
 
117
 
 
118
 
 
119
def iter_ancestors(revision_id, revision_source, only_present=False):
 
120
    ancestors = (revision_id,)
 
121
    distance = 0
 
122
    while len(ancestors) > 0:
 
123
        new_ancestors = []
 
124
        for ancestor in ancestors:
 
125
            if not only_present:
 
126
                yield ancestor, distance
 
127
            try:
 
128
                revision = revision_source.get_revision(ancestor)
 
129
            except bzrlib.errors.NoSuchRevision, e:
 
130
                if e.revision == revision_id:
 
131
                    raise 
 
132
                else:
 
133
                    continue
 
134
            if only_present:
 
135
                yield ancestor, distance
 
136
            new_ancestors.extend(revision.parent_ids)
 
137
        ancestors = new_ancestors
 
138
        distance += 1
 
139
 
 
140
 
 
141
def find_present_ancestors(revision_id, revision_source):
 
142
    """Return the ancestors of a revision present in a branch.
 
143
 
 
144
    It's possible that a branch won't have the complete ancestry of
 
145
    one of its revisions.  
 
146
 
 
147
    """
 
148
    found_ancestors = {}
 
149
    anc_iter = enumerate(iter_ancestors(revision_id, revision_source,
 
150
                         only_present=True))
 
151
    for anc_order, (anc_id, anc_distance) in anc_iter:
 
152
        if not found_ancestors.has_key(anc_id):
 
153
            found_ancestors[anc_id] = (anc_order, anc_distance)
 
154
    return found_ancestors
 
155
    
 
156
 
 
157
def __get_closest(intersection):
 
158
    intersection.sort()
 
159
    matches = [] 
 
160
    for entry in intersection:
 
161
        if entry[0] == intersection[0][0]:
 
162
            matches.append(entry[2])
 
163
    return matches
 
164
 
 
165
 
 
166
def revision_graph(revision, revision_source):
 
167
    """Produce a graph of the ancestry of the specified revision.
 
168
    
 
169
    :return: root, ancestors map, descendants map
 
170
    """
 
171
    revision_source.lock_read()
 
172
    try:
 
173
        return _revision_graph(revision, revision_source)
 
174
    finally:
 
175
        revision_source.unlock()
 
176
 
 
177
 
 
178
def _revision_graph(revision, revision_source):
 
179
    """See revision_graph."""
 
180
    from bzrlib.tsort import topo_sort
 
181
    graph = revision_source.get_revision_graph(revision)
 
182
    # mark all no-parent revisions as being NULL_REVISION parentage.
 
183
    for node, parents in graph.items():
 
184
        if len(parents) == 0:
 
185
            graph[node] = [NULL_REVISION]
 
186
    # add NULL_REVISION to the graph
 
187
    graph[NULL_REVISION] = []
 
188
 
 
189
    # pick a root. If there are multiple roots
 
190
    # this could pick a random one.
 
191
    topo_order = topo_sort(graph.items())
 
192
    root = topo_order[0]
 
193
 
 
194
    ancestors = {}
 
195
    descendants = {}
 
196
 
 
197
    # map the descendants of the graph.
 
198
    # and setup our set based return graph.
 
199
    for node in graph.keys():
 
200
        descendants[node] = {}
 
201
    for node, parents in graph.items():
 
202
        for parent in parents:
 
203
            descendants[parent][node] = 1
 
204
        ancestors[node] = set(parents)
 
205
 
 
206
    assert root not in descendants[root]
 
207
    assert root not in ancestors[root]
 
208
    return root, ancestors, descendants
 
209
 
 
210
 
 
211
def combined_graph(revision_a, revision_b, revision_source):
 
212
    """Produce a combined ancestry graph.
 
213
    Return graph root, ancestors map, descendants map, set of common nodes"""
 
214
    root, ancestors, descendants = revision_graph(
 
215
        revision_a, revision_source)
 
216
    root_b, ancestors_b, descendants_b = revision_graph(
 
217
        revision_b, revision_source)
 
218
    if root != root_b:
 
219
        raise bzrlib.errors.NoCommonRoot(revision_a, revision_b)
 
220
    common = set()
 
221
    for node, node_anc in ancestors_b.iteritems():
 
222
        if node in ancestors:
 
223
            common.add(node)
 
224
        else:
 
225
            ancestors[node] = set()
 
226
        ancestors[node].update(node_anc)
 
227
    for node, node_dec in descendants_b.iteritems():
 
228
        if node not in descendants:
 
229
            descendants[node] = {}
 
230
        descendants[node].update(node_dec)
 
231
    return root, ancestors, descendants, common
 
232
 
 
233
 
 
234
def common_ancestor(revision_a, revision_b, revision_source, 
 
235
                    pb=DummyProgress()):
 
236
    if None in (revision_a, revision_b):
 
237
        return None
 
238
    # trivial optimisation
 
239
    if revision_a == revision_b:
 
240
        return revision_a
 
241
    try:
 
242
        try:
 
243
            pb.update('Picking ancestor', 1, 3)
 
244
            graph = revision_source.get_revision_graph_with_ghosts(
 
245
                [revision_a, revision_b])
 
246
            # convert to a NULL_REVISION based graph.
 
247
            ancestors = graph.get_ancestors()
 
248
            descendants = graph.get_descendants()
 
249
            common = set(graph.get_ancestry(revision_a)).intersection(
 
250
                     set(graph.get_ancestry(revision_b)))
 
251
            descendants[NULL_REVISION] = {}
 
252
            ancestors[NULL_REVISION] = []
 
253
            for root in graph.roots:
 
254
                descendants[NULL_REVISION][root] = 1
 
255
                ancestors[root].append(NULL_REVISION)
 
256
            for ghost in graph.ghosts:
 
257
                # ghosts act as roots for the purpose of finding 
 
258
                # the longest paths from the root: any ghost *might*
 
259
                # be directly attached to the root, so we treat them
 
260
                # as being such.
 
261
                # ghost now descends from NULL
 
262
                descendants[NULL_REVISION][ghost] = 1
 
263
                # that is it has an ancestor of NULL
 
264
                ancestors[ghost] = [NULL_REVISION]
 
265
                # ghost is common if any of ghosts descendants are common:
 
266
                for ghost_descendant in descendants[ghost]:
 
267
                    if ghost_descendant in common:
 
268
                        common.add(ghost)
 
269
                
 
270
            root = NULL_REVISION
 
271
            common.add(NULL_REVISION)
 
272
        except bzrlib.errors.NoCommonRoot:
 
273
            raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
 
274
            
 
275
        pb.update('Picking ancestor', 2, 3)
 
276
        distances = node_distances (descendants, ancestors, root)
 
277
        pb.update('Picking ancestor', 3, 2)
 
278
        farthest = select_farthest(distances, common)
 
279
        if farthest is None or farthest == NULL_REVISION:
 
280
            raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
 
281
    finally:
 
282
        pb.clear()
 
283
    return farthest
 
284
 
 
285
 
 
286
class MultipleRevisionSources(object):
 
287
    """Proxy that looks in multiple branches for revisions."""
 
288
    def __init__(self, *args):
 
289
        object.__init__(self)
 
290
        assert len(args) != 0
 
291
        self._revision_sources = args
 
292
 
 
293
    def revision_parents(self, revision_id):
 
294
        for source in self._revision_sources:
 
295
            try:
 
296
                return source.revision_parents(revision_id)
 
297
            except (errors.WeaveRevisionNotPresent, errors.NoSuchRevision), e:
 
298
                pass
 
299
        raise e
 
300
 
 
301
    def get_revision(self, revision_id):
 
302
        for source in self._revision_sources:
 
303
            try:
 
304
                return source.get_revision(revision_id)
 
305
            except bzrlib.errors.NoSuchRevision, e:
 
306
                pass
 
307
        raise e
 
308
 
 
309
    def get_revision_graph(self, revision_id):
 
310
        # we could probe incrementally until the pending
 
311
        # ghosts list stop growing, but its cheaper for now
 
312
        # to just ask for the complete graph for each repository.
 
313
        graphs = []
 
314
        for source in self._revision_sources:
 
315
            ghost_graph = source.get_revision_graph_with_ghosts()
 
316
            graphs.append(ghost_graph)
 
317
        absent = 0
 
318
        for graph in graphs:
 
319
            if not revision_id in graph.get_ancestors():
 
320
                absent += 1
 
321
        if absent == len(graphs):
 
322
            raise errors.NoSuchRevision(self._revision_sources[0], revision_id)
 
323
 
 
324
        # combine the graphs
 
325
        result = {}
 
326
        pending = set([revision_id])
 
327
        def find_parents(node_id):
 
328
            """find the parents for node_id."""
 
329
            for graph in graphs:
 
330
                ancestors = graph.get_ancestors()
 
331
                try:
 
332
                    return ancestors[node_id]
 
333
                except KeyError:
 
334
                    pass
 
335
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
 
336
        while len(pending):
 
337
            # all the graphs should have identical parent lists
 
338
            node_id = pending.pop()
 
339
            try:
 
340
                result[node_id] = find_parents(node_id)
 
341
                for parent_node in result[node_id]:
 
342
                    if not parent_node in result:
 
343
                        pending.add(parent_node)
 
344
            except errors.NoSuchRevision:
 
345
                # ghost, ignore it.
 
346
                pass
 
347
        return result
 
348
 
 
349
    def get_revision_graph_with_ghosts(self, revision_ids):
 
350
        # query all the sources for their entire graphs 
 
351
        # and then build a combined graph for just
 
352
        # revision_ids.
 
353
        graphs = []
 
354
        for source in self._revision_sources:
 
355
            ghost_graph = source.get_revision_graph_with_ghosts()
 
356
            graphs.append(ghost_graph.get_ancestors())
 
357
        for revision_id in revision_ids:
 
358
            absent = 0
 
359
            for graph in graphs:
 
360
                    if not revision_id in graph:
 
361
                        absent += 1
 
362
            if absent == len(graphs):
 
363
                raise errors.NoSuchRevision(self._revision_sources[0],
 
364
                                            revision_id)
 
365
 
 
366
        # combine the graphs
 
367
        result = Graph()
 
368
        pending = set(revision_ids)
 
369
        done = set()
 
370
        def find_parents(node_id):
 
371
            """find the parents for node_id."""
 
372
            for graph in graphs:
 
373
                try:
 
374
                    return graph[node_id]
 
375
                except KeyError:
 
376
                    pass
 
377
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
 
378
        while len(pending):
 
379
            # all the graphs should have identical parent lists
 
380
            node_id = pending.pop()
 
381
            try:
 
382
                parents = find_parents(node_id)
 
383
                for parent_node in parents:
 
384
                    # queued or done? 
 
385
                    if (parent_node not in pending and
 
386
                        parent_node not in done):
 
387
                        # no, queue
 
388
                        pending.add(parent_node)
 
389
                result.add_node(node_id, parents)
 
390
                done.add(node_id)
 
391
            except errors.NoSuchRevision:
 
392
                # ghost
 
393
                result.add_ghost(node_id)
 
394
                continue
 
395
        return result
 
396
 
 
397
    def lock_read(self):
 
398
        for source in self._revision_sources:
 
399
            source.lock_read()
 
400
 
 
401
    def unlock(self):
 
402
        for source in self._revision_sources:
 
403
            source.unlock()