~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revision.py

  • Committer: Martin Pool
  • Date: 2005-09-30 03:43:58 UTC
  • mto: (1185.14.2)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: mbp@sourcefrog.net-20050930034358-f2acb25d7b5e756a
- set new version for this branch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical
 
1
# (C) 2005 Canonical
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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
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 as errors
22
 
from bzrlib.graph import node_distances, select_farthest, all_descendants, Graph
23
 
from bzrlib.osutils import contains_whitespace
24
 
from bzrlib.progress import DummyProgress
25
 
from bzrlib.symbol_versioning import (deprecated_function,
26
 
        zero_eight,
27
 
        )
 
17
 
 
18
import bzrlib.errors
 
19
from bzrlib.graph import node_distances, select_farthest, all_descendants
28
20
 
29
21
NULL_REVISION="null:"
30
22
 
39
31
 
40
32
    parent_ids
41
33
        List of parent revision_ids
42
 
 
43
 
    properties
44
 
        Dictionary of revision properties.  These are attached to the
45
 
        revision as extra metadata.  The name must be a single 
46
 
        word; the value can be an arbitrary string.
47
34
    """
 
35
    inventory_id = None
 
36
    inventory_sha1 = None
 
37
    revision_id = None
 
38
    timestamp = None
 
39
    message = None
 
40
    timezone = None
 
41
    committer = None
48
42
    
49
 
    def __init__(self, revision_id, properties=None, **args):
50
 
        self.revision_id = revision_id
51
 
        self.properties = properties or {}
52
 
        self._check_properties()
 
43
    def __init__(self, **args):
 
44
        self.__dict__.update(args)
53
45
        self.parent_ids = []
54
46
        self.parent_sha1s = []
55
 
        """Not used anymore - legacy from for 4."""
56
 
        self.__dict__.update(args)
 
47
 
57
48
 
58
49
    def __repr__(self):
59
50
        return "<Revision id %s>" % self.revision_id
61
52
    def __eq__(self, other):
62
53
        if not isinstance(other, Revision):
63
54
            return False
64
 
        # FIXME: rbc 20050930 parent_ids are not being compared
65
 
        return (
66
 
                self.inventory_sha1 == other.inventory_sha1
 
55
        return (self.inventory_id == other.inventory_id
 
56
                and self.inventory_sha1 == other.inventory_sha1
67
57
                and self.revision_id == other.revision_id
68
58
                and self.timestamp == other.timestamp
69
59
                and self.message == other.message
70
60
                and self.timezone == other.timezone
71
 
                and self.committer == other.committer
72
 
                and self.properties == other.properties)
 
61
                and self.committer == other.committer)
73
62
 
74
63
    def __ne__(self, other):
75
64
        return not self.__eq__(other)
76
65
 
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
 
    def get_summary(self):
107
 
        """Get the first line of the log message for this revision.
108
 
        """
109
 
        return self.message.split('\n', 1)[0]
 
66
        
 
67
 
 
68
REVISION_ID_RE = None
 
69
 
 
70
def validate_revision_id(rid):
 
71
    """Check rid is syntactically valid for a revision id."""
 
72
    global REVISION_ID_RE
 
73
    if not REVISION_ID_RE:
 
74
        import re
 
75
        REVISION_ID_RE = re.compile('[\w.-]+@[\w.-]+--?\d+--?[0-9a-f]+\Z')
 
76
 
 
77
    if not REVISION_ID_RE.match(rid):
 
78
        raise ValueError("malformed revision-id %r" % rid)
110
79
 
111
80
 
112
81
def is_ancestor(revision_id, candidate_id, branch):
118
87
    revisions_source is an object supporting a get_revision operation that
119
88
    behaves like Branch's.
120
89
    """
121
 
    return candidate_id in branch.repository.get_ancestry(revision_id)
 
90
    return candidate_id in branch.get_ancestry(revision_id)
122
91
 
123
92
 
124
93
def iter_ancestors(revision_id, revision_source, only_present=False):
131
100
                yield ancestor, distance
132
101
            try:
133
102
                revision = revision_source.get_revision(ancestor)
134
 
            except errors.NoSuchRevision, e:
 
103
            except bzrlib.errors.NoSuchRevision, e:
135
104
                if e.revision == revision_id:
136
105
                    raise 
137
106
                else:
168
137
    return matches
169
138
 
170
139
 
 
140
def old_common_ancestor(revision_a, revision_b, revision_source):
 
141
    """Find the ancestor common to both revisions that is closest to both.
 
142
    """
 
143
    from bzrlib.trace import mutter
 
144
    a_ancestors = find_present_ancestors(revision_a, revision_source)
 
145
    b_ancestors = find_present_ancestors(revision_b, revision_source)
 
146
    a_intersection = []
 
147
    b_intersection = []
 
148
    # a_order is used as a tie-breaker when two equally-good bases are found
 
149
    for revision, (a_order, a_distance) in a_ancestors.iteritems():
 
150
        if b_ancestors.has_key(revision):
 
151
            a_intersection.append((a_distance, a_order, revision))
 
152
            b_intersection.append((b_ancestors[revision][1], a_order, revision))
 
153
    mutter("a intersection: %r" % a_intersection)
 
154
    mutter("b intersection: %r" % b_intersection)
 
155
 
 
156
    a_closest = __get_closest(a_intersection)
 
157
    if len(a_closest) == 0:
 
158
        return None
 
159
    b_closest = __get_closest(b_intersection)
 
160
    assert len(b_closest) != 0
 
161
    mutter ("a_closest %r" % a_closest)
 
162
    mutter ("b_closest %r" % b_closest)
 
163
    if a_closest[0] in b_closest:
 
164
        return a_closest[0]
 
165
    elif b_closest[0] in a_closest:
 
166
        return b_closest[0]
 
167
    else:
 
168
        raise bzrlib.errors.AmbiguousBase((a_closest[0], b_closest[0]))
 
169
    return a_closest[0]
 
170
 
171
171
def revision_graph(revision, revision_source):
172
172
    """Produce a graph of the ancestry of the specified revision.
173
 
    
174
 
    :return: root, ancestors map, descendants map
 
173
    Return root, ancestors map, descendants map
 
174
 
 
175
    TODO: Produce graphs with the NULL revision as root, so that we can find
 
176
    a common even when trees are not branches don't represent a single line
 
177
    of descent.
175
178
    """
176
 
    revision_source.lock_read()
177
 
    try:
178
 
        return _revision_graph(revision, revision_source)
179
 
    finally:
180
 
        revision_source.unlock()
181
 
 
182
 
 
183
 
def _revision_graph(revision, revision_source):
184
 
    """See revision_graph."""
185
 
    from bzrlib.tsort import topo_sort
186
 
    graph = revision_source.get_revision_graph(revision)
187
 
    # mark all no-parent revisions as being NULL_REVISION parentage.
188
 
    for node, parents in graph.items():
189
 
        if len(parents) == 0:
190
 
            graph[node] = [NULL_REVISION]
191
 
    # add NULL_REVISION to the graph
192
 
    graph[NULL_REVISION] = []
193
 
 
194
 
    # pick a root. If there are multiple roots
195
 
    # this could pick a random one.
196
 
    topo_order = topo_sort(graph.items())
197
 
    root = topo_order[0]
198
 
 
199
179
    ancestors = {}
200
180
    descendants = {}
201
 
 
202
 
    # map the descendants of the graph.
203
 
    # and setup our set based return graph.
204
 
    for node in graph.keys():
205
 
        descendants[node] = {}
206
 
    for node, parents in graph.items():
207
 
        for parent in parents:
208
 
            descendants[parent][node] = 1
209
 
        ancestors[node] = set(parents)
210
 
 
 
181
    lines = [revision]
 
182
    root = None
 
183
    descendants[revision] = {}
 
184
    while len(lines) > 0:
 
185
        new_lines = set()
 
186
        for line in lines:
 
187
            if line == NULL_REVISION:
 
188
                parents = []
 
189
                root = NULL_REVISION
 
190
            else:
 
191
                try:
 
192
                    rev = revision_source.get_revision(line)
 
193
                    parents = list(rev.parent_ids)
 
194
                    if len(parents) == 0:
 
195
                        parents = [NULL_REVISION]
 
196
                except bzrlib.errors.NoSuchRevision:
 
197
                    if line == revision:
 
198
                        raise
 
199
                    parents = None
 
200
            if parents is not None:
 
201
                for parent in parents:
 
202
                    if parent not in ancestors:
 
203
                        new_lines.add(parent)
 
204
                    if parent not in descendants:
 
205
                        descendants[parent] = {}
 
206
                    descendants[parent][line] = 1
 
207
            if parents is not None:
 
208
                ancestors[line] = set(parents)
 
209
        lines = new_lines
211
210
    assert root not in descendants[root]
212
211
    assert root not in ancestors[root]
213
212
    return root, ancestors, descendants
214
213
 
215
 
 
216
214
def combined_graph(revision_a, revision_b, revision_source):
217
215
    """Produce a combined ancestry graph.
218
216
    Return graph root, ancestors map, descendants map, set of common nodes"""
219
 
    root, ancestors, descendants = revision_graph(
220
 
        revision_a, revision_source)
221
 
    root_b, ancestors_b, descendants_b = revision_graph(
222
 
        revision_b, revision_source)
 
217
    root, ancestors, descendants = revision_graph(revision_a, revision_source)
 
218
    root_b, ancestors_b, descendants_b = revision_graph(revision_b, 
 
219
                                                        revision_source)
223
220
    if root != root_b:
224
 
        raise errors.NoCommonRoot(revision_a, revision_b)
 
221
        raise bzrlib.errors.NoCommonRoot(revision_a, revision_b)
225
222
    common = set()
226
223
    for node, node_anc in ancestors_b.iteritems():
227
224
        if node in ancestors:
235
232
        descendants[node].update(node_dec)
236
233
    return root, ancestors, descendants, common
237
234
 
238
 
 
239
 
def common_ancestor(revision_a, revision_b, revision_source, 
240
 
                    pb=DummyProgress()):
241
 
    if None in (revision_a, revision_b):
242
 
        return None
243
 
    # trivial optimisation
244
 
    if revision_a == revision_b:
245
 
        return revision_a
 
235
def common_ancestor(revision_a, revision_b, revision_source):
246
236
    try:
247
 
        try:
248
 
            pb.update('Picking ancestor', 1, 3)
249
 
            graph = revision_source.get_revision_graph_with_ghosts(
250
 
                [revision_a, revision_b])
251
 
            # convert to a NULL_REVISION based graph.
252
 
            ancestors = graph.get_ancestors()
253
 
            descendants = graph.get_descendants()
254
 
            common = set(graph.get_ancestry(revision_a)).intersection(
255
 
                     set(graph.get_ancestry(revision_b)))
256
 
            descendants[NULL_REVISION] = {}
257
 
            ancestors[NULL_REVISION] = []
258
 
            for root in graph.roots:
259
 
                descendants[NULL_REVISION][root] = 1
260
 
                ancestors[root].append(NULL_REVISION)
261
 
            for ghost in graph.ghosts:
262
 
                # ghosts act as roots for the purpose of finding 
263
 
                # the longest paths from the root: any ghost *might*
264
 
                # be directly attached to the root, so we treat them
265
 
                # as being such.
266
 
                # ghost now descends from NULL
267
 
                descendants[NULL_REVISION][ghost] = 1
268
 
                # that is it has an ancestor of NULL
269
 
                ancestors[ghost] = [NULL_REVISION]
270
 
                # ghost is common if any of ghosts descendants are common:
271
 
                for ghost_descendant in descendants[ghost]:
272
 
                    if ghost_descendant in common:
273
 
                        common.add(ghost)
274
 
                
275
 
            root = NULL_REVISION
276
 
            common.add(NULL_REVISION)
277
 
        except errors.NoCommonRoot:
278
 
            raise errors.NoCommonAncestor(revision_a, revision_b)
279
 
            
280
 
        pb.update('Picking ancestor', 2, 3)
281
 
        distances = node_distances (descendants, ancestors, root)
282
 
        pb.update('Picking ancestor', 3, 2)
283
 
        farthest = select_farthest(distances, common)
284
 
        if farthest is None or farthest == NULL_REVISION:
285
 
            raise errors.NoCommonAncestor(revision_a, revision_b)
286
 
    finally:
287
 
        pb.clear()
 
237
        root, ancestors, descendants, common = \
 
238
            combined_graph(revision_a, revision_b, revision_source)
 
239
    except bzrlib.errors.NoCommonRoot:
 
240
        raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
 
241
        
 
242
    distances = node_distances (descendants, ancestors, root)
 
243
    farthest = select_farthest(distances, common)
 
244
    if farthest is None or farthest == NULL_REVISION:
 
245
        raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
288
246
    return farthest
289
247
 
290
 
 
291
248
class MultipleRevisionSources(object):
292
249
    """Proxy that looks in multiple branches for revisions."""
293
250
    def __init__(self, *args):
295
252
        assert len(args) != 0
296
253
        self._revision_sources = args
297
254
 
298
 
    def revision_parents(self, revision_id):
299
 
        for source in self._revision_sources:
300
 
            try:
301
 
                return source.revision_parents(revision_id)
302
 
            except (errors.WeaveRevisionNotPresent, errors.NoSuchRevision), e:
303
 
                pass
304
 
        raise e
305
 
 
306
255
    def get_revision(self, revision_id):
307
256
        for source in self._revision_sources:
308
257
            try:
309
258
                return source.get_revision(revision_id)
310
 
            except errors.NoSuchRevision, e:
 
259
            except bzrlib.errors.NoSuchRevision, e:
311
260
                pass
312
261
        raise e
313
262
 
314
 
    def get_revision_graph(self, revision_id):
315
 
        # we could probe incrementally until the pending
316
 
        # ghosts list stop growing, but its cheaper for now
317
 
        # to just ask for the complete graph for each repository.
318
 
        graphs = []
319
 
        for source in self._revision_sources:
320
 
            ghost_graph = source.get_revision_graph_with_ghosts()
321
 
            graphs.append(ghost_graph)
322
 
        absent = 0
323
 
        for graph in graphs:
324
 
            if not revision_id in graph.get_ancestors():
325
 
                absent += 1
326
 
        if absent == len(graphs):
327
 
            raise errors.NoSuchRevision(self._revision_sources[0], revision_id)
328
 
 
329
 
        # combine the graphs
330
 
        result = {}
331
 
        pending = set([revision_id])
332
 
        def find_parents(node_id):
333
 
            """find the parents for node_id."""
334
 
            for graph in graphs:
335
 
                ancestors = graph.get_ancestors()
336
 
                try:
337
 
                    return ancestors[node_id]
338
 
                except KeyError:
339
 
                    pass
340
 
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
341
 
        while len(pending):
342
 
            # all the graphs should have identical parent lists
343
 
            node_id = pending.pop()
344
 
            try:
345
 
                result[node_id] = find_parents(node_id)
346
 
                for parent_node in result[node_id]:
347
 
                    if not parent_node in result:
348
 
                        pending.add(parent_node)
349
 
            except errors.NoSuchRevision:
350
 
                # ghost, ignore it.
351
 
                pass
352
 
        return result
353
 
 
354
 
    def get_revision_graph_with_ghosts(self, revision_ids):
355
 
        # query all the sources for their entire graphs 
356
 
        # and then build a combined graph for just
357
 
        # revision_ids.
358
 
        graphs = []
359
 
        for source in self._revision_sources:
360
 
            ghost_graph = source.get_revision_graph_with_ghosts()
361
 
            graphs.append(ghost_graph.get_ancestors())
362
 
        for revision_id in revision_ids:
363
 
            absent = 0
364
 
            for graph in graphs:
365
 
                    if not revision_id in graph:
366
 
                        absent += 1
367
 
            if absent == len(graphs):
368
 
                raise errors.NoSuchRevision(self._revision_sources[0],
369
 
                                            revision_id)
370
 
 
371
 
        # combine the graphs
372
 
        result = Graph()
373
 
        pending = set(revision_ids)
374
 
        done = set()
375
 
        def find_parents(node_id):
376
 
            """find the parents for node_id."""
377
 
            for graph in graphs:
378
 
                try:
379
 
                    return graph[node_id]
380
 
                except KeyError:
381
 
                    pass
382
 
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
383
 
        while len(pending):
384
 
            # all the graphs should have identical parent lists
385
 
            node_id = pending.pop()
386
 
            try:
387
 
                parents = find_parents(node_id)
388
 
                for parent_node in parents:
389
 
                    # queued or done? 
390
 
                    if (parent_node not in pending and
391
 
                        parent_node not in done):
392
 
                        # no, queue
393
 
                        pending.add(parent_node)
394
 
                result.add_node(node_id, parents)
395
 
                done.add(node_id)
396
 
            except errors.NoSuchRevision:
397
 
                # ghost
398
 
                result.add_ghost(node_id)
399
 
                continue
400
 
        return result
401
 
 
402
 
    def lock_read(self):
403
 
        for source in self._revision_sources:
404
 
            source.lock_read()
405
 
 
406
 
    def unlock(self):
407
 
        for source in self._revision_sources:
408
 
            source.unlock()
409
 
 
410
 
 
411
 
@deprecated_function(zero_eight)
412
 
def get_intervening_revisions(ancestor_id, rev_id, rev_source,
 
263
def get_intervening_revisions(ancestor_id, rev_id, rev_source, 
413
264
                              revision_history=None):
414
265
    """Find the longest line of descent from maybe_ancestor to revision.
415
266
    Revision history is followed where possible.
420
271
    """
421
272
    root, ancestors, descendants = revision_graph(rev_id, rev_source)
422
273
    if len(descendants) == 0:
423
 
        raise errors.NoSuchRevision(rev_source, rev_id)
 
274
        raise NoSuchRevision(rev_source, rev_id)
424
275
    if ancestor_id not in descendants:
425
276
        rev_source.get_revision(ancestor_id)
426
 
        raise errors.NotAncestor(rev_id, ancestor_id)
 
277
        raise bzrlib.errors.NotAncestor(rev_id, ancestor_id)
427
278
    root_descendants = all_descendants(descendants, ancestor_id)
428
279
    root_descendants.add(ancestor_id)
429
280
    if rev_id not in root_descendants:
430
 
        raise errors.NotAncestor(rev_id, ancestor_id)
 
281
        raise bzrlib.errors.NotAncestor(rev_id, ancestor_id)
431
282
    distances = node_distances(descendants, ancestors, ancestor_id,
432
283
                               root_descendants=root_descendants)
433
284