~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 05:56:05 UTC
  • mto: (1185.14.2)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: mbp@sourcefrog.net-20050930055605-a2c534529b392a7d
- fix upgrade for transport changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
2
 
#
 
1
# (C) 2005 Canonical
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
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
 
CURRENT_REVISION="current:"
31
 
 
32
22
 
33
23
class Revision(object):
34
24
    """Single revision on a branch.
41
31
 
42
32
    parent_ids
43
33
        List of parent revision_ids
44
 
 
45
 
    properties
46
 
        Dictionary of revision properties.  These are attached to the
47
 
        revision as extra metadata.  The name must be a single 
48
 
        word; the value can be an arbitrary string.
49
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
50
42
    
51
 
    def __init__(self, revision_id, properties=None, **args):
52
 
        self.revision_id = revision_id
53
 
        self.properties = properties or {}
54
 
        self._check_properties()
 
43
    def __init__(self, **args):
 
44
        self.__dict__.update(args)
55
45
        self.parent_ids = []
56
46
        self.parent_sha1s = []
57
 
        """Not used anymore - legacy from for 4."""
58
 
        self.__dict__.update(args)
 
47
 
59
48
 
60
49
    def __repr__(self):
61
50
        return "<Revision id %s>" % self.revision_id
63
52
    def __eq__(self, other):
64
53
        if not isinstance(other, Revision):
65
54
            return False
66
 
        # FIXME: rbc 20050930 parent_ids are not being compared
67
 
        return (
68
 
                self.inventory_sha1 == other.inventory_sha1
 
55
        return (self.inventory_id == other.inventory_id
 
56
                and self.inventory_sha1 == other.inventory_sha1
69
57
                and self.revision_id == other.revision_id
70
58
                and self.timestamp == other.timestamp
71
59
                and self.message == other.message
72
60
                and self.timezone == other.timezone
73
 
                and self.committer == other.committer
74
 
                and self.properties == other.properties)
 
61
                and self.committer == other.committer)
75
62
 
76
63
    def __ne__(self, other):
77
64
        return not self.__eq__(other)
78
65
 
79
 
    def _check_properties(self):
80
 
        """Verify that all revision properties are OK."""
81
 
        for name, value in self.properties.iteritems():
82
 
            if not isinstance(name, basestring) or contains_whitespace(name):
83
 
                raise ValueError("invalid property name %r" % name)
84
 
            if not isinstance(value, basestring):
85
 
                raise ValueError("invalid property value %r for %r" % 
86
 
                                 (name, value))
87
 
 
88
 
    def get_history(self, repository):
89
 
        """Return the canonical line-of-history for this revision.
90
 
 
91
 
        If ghosts are present this may differ in result from a ghost-free
92
 
        repository.
93
 
        """
94
 
        current_revision = self
95
 
        reversed_result = []
96
 
        while current_revision is not None:
97
 
            reversed_result.append(current_revision.revision_id)
98
 
            if not len (current_revision.parent_ids):
99
 
                reversed_result.append(None)
100
 
                current_revision = None
101
 
            else:
102
 
                next_revision_id = current_revision.parent_ids[0]
103
 
                current_revision = repository.get_revision(next_revision_id)
104
 
        reversed_result.reverse()
105
 
        return reversed_result
106
 
 
107
 
    def get_summary(self):
108
 
        """Get the first line of the log message for this revision.
109
 
        """
110
 
        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)
111
79
 
112
80
 
113
81
def is_ancestor(revision_id, candidate_id, branch):
119
87
    revisions_source is an object supporting a get_revision operation that
120
88
    behaves like Branch's.
121
89
    """
122
 
    return (candidate_id in branch.repository.get_ancestry(revision_id))
 
90
    return candidate_id in branch.get_ancestry(revision_id)
123
91
 
124
92
 
125
93
def iter_ancestors(revision_id, revision_source, only_present=False):
132
100
                yield ancestor, distance
133
101
            try:
134
102
                revision = revision_source.get_revision(ancestor)
135
 
            except errors.NoSuchRevision, e:
 
103
            except bzrlib.errors.NoSuchRevision, e:
136
104
                if e.revision == revision_id:
137
105
                    raise 
138
106
                else:
155
123
    anc_iter = enumerate(iter_ancestors(revision_id, revision_source,
156
124
                         only_present=True))
157
125
    for anc_order, (anc_id, anc_distance) in anc_iter:
158
 
        if anc_id not in found_ancestors:
 
126
        if not found_ancestors.has_key(anc_id):
159
127
            found_ancestors[anc_id] = (anc_order, anc_distance)
160
128
    return found_ancestors
161
129
    
169
137
    return matches
170
138
 
171
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
 
172
171
def revision_graph(revision, revision_source):
173
172
    """Produce a graph of the ancestry of the specified revision.
174
 
    
175
 
    :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.
176
178
    """
177
 
    revision_source.lock_read()
178
 
    try:
179
 
        return _revision_graph(revision, revision_source)
180
 
    finally:
181
 
        revision_source.unlock()
182
 
 
183
 
 
184
 
def _revision_graph(revision, revision_source):
185
 
    """See revision_graph."""
186
 
    from bzrlib.tsort import topo_sort
187
 
    graph = revision_source.get_revision_graph(revision)
188
 
    # mark all no-parent revisions as being NULL_REVISION parentage.
189
 
    for node, parents in graph.items():
190
 
        if len(parents) == 0:
191
 
            graph[node] = [NULL_REVISION]
192
 
    # add NULL_REVISION to the graph
193
 
    graph[NULL_REVISION] = []
194
 
 
195
 
    # pick a root. If there are multiple roots
196
 
    # this could pick a random one.
197
 
    topo_order = topo_sort(graph.items())
198
 
    root = topo_order[0]
199
 
 
200
179
    ancestors = {}
201
180
    descendants = {}
202
 
 
203
 
    # map the descendants of the graph.
204
 
    # and setup our set based return graph.
205
 
    for node in graph.keys():
206
 
        descendants[node] = {}
207
 
    for node, parents in graph.items():
208
 
        for parent in parents:
209
 
            descendants[parent][node] = 1
210
 
        ancestors[node] = set(parents)
211
 
 
 
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
212
210
    assert root not in descendants[root]
213
211
    assert root not in ancestors[root]
214
212
    return root, ancestors, descendants
215
213
 
216
 
 
217
214
def combined_graph(revision_a, revision_b, revision_source):
218
215
    """Produce a combined ancestry graph.
219
216
    Return graph root, ancestors map, descendants map, set of common nodes"""
220
 
    root, ancestors, descendants = revision_graph(
221
 
        revision_a, revision_source)
222
 
    root_b, ancestors_b, descendants_b = revision_graph(
223
 
        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)
224
220
    if root != root_b:
225
 
        raise errors.NoCommonRoot(revision_a, revision_b)
 
221
        raise bzrlib.errors.NoCommonRoot(revision_a, revision_b)
226
222
    common = set()
227
223
    for node, node_anc in ancestors_b.iteritems():
228
224
        if node in ancestors:
236
232
        descendants[node].update(node_dec)
237
233
    return root, ancestors, descendants, common
238
234
 
239
 
 
240
 
def common_ancestor(revision_a, revision_b, revision_source, 
241
 
                    pb=DummyProgress()):
242
 
    if None in (revision_a, revision_b):
243
 
        return None
244
 
    if NULL_REVISION in (revision_a, revision_b):
245
 
        return NULL_REVISION
246
 
    # trivial optimisation
247
 
    if revision_a == revision_b:
248
 
        return revision_a
 
235
def common_ancestor(revision_a, revision_b, revision_source):
249
236
    try:
250
 
        try:
251
 
            pb.update('Picking ancestor', 1, 3)
252
 
            graph = revision_source.get_revision_graph_with_ghosts(
253
 
                [revision_a, revision_b])
254
 
            # convert to a NULL_REVISION based graph.
255
 
            ancestors = graph.get_ancestors()
256
 
            descendants = graph.get_descendants()
257
 
            common = set(graph.get_ancestry(revision_a)).intersection(
258
 
                     set(graph.get_ancestry(revision_b)))
259
 
            descendants[NULL_REVISION] = {}
260
 
            ancestors[NULL_REVISION] = []
261
 
            for root in graph.roots:
262
 
                descendants[NULL_REVISION][root] = 1
263
 
                ancestors[root].append(NULL_REVISION)
264
 
            for ghost in graph.ghosts:
265
 
                # ghosts act as roots for the purpose of finding 
266
 
                # the longest paths from the root: any ghost *might*
267
 
                # be directly attached to the root, so we treat them
268
 
                # as being such.
269
 
                # ghost now descends from NULL
270
 
                descendants[NULL_REVISION][ghost] = 1
271
 
                # that is it has an ancestor of NULL
272
 
                ancestors[ghost] = [NULL_REVISION]
273
 
                # ghost is common if any of ghosts descendants are common:
274
 
                for ghost_descendant in descendants[ghost]:
275
 
                    if ghost_descendant in common:
276
 
                        common.add(ghost)
277
 
                
278
 
            root = NULL_REVISION
279
 
            common.add(NULL_REVISION)
280
 
        except errors.NoCommonRoot:
281
 
            raise errors.NoCommonAncestor(revision_a, revision_b)
282
 
            
283
 
        pb.update('Picking ancestor', 2, 3)
284
 
        distances = node_distances (descendants, ancestors, root)
285
 
        pb.update('Picking ancestor', 3, 2)
286
 
        farthest = select_farthest(distances, common)
287
 
        if farthest is None or farthest == NULL_REVISION:
288
 
            raise errors.NoCommonAncestor(revision_a, revision_b)
289
 
    finally:
290
 
        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)
291
246
    return farthest
292
247
 
293
 
 
294
248
class MultipleRevisionSources(object):
295
249
    """Proxy that looks in multiple branches for revisions."""
296
250
    def __init__(self, *args):
298
252
        assert len(args) != 0
299
253
        self._revision_sources = args
300
254
 
301
 
    def revision_parents(self, revision_id):
302
 
        for source in self._revision_sources:
303
 
            try:
304
 
                return source.revision_parents(revision_id)
305
 
            except (errors.WeaveRevisionNotPresent, errors.NoSuchRevision), e:
306
 
                pass
307
 
        raise e
308
 
 
309
255
    def get_revision(self, revision_id):
310
256
        for source in self._revision_sources:
311
257
            try:
312
258
                return source.get_revision(revision_id)
313
 
            except errors.NoSuchRevision, e:
 
259
            except bzrlib.errors.NoSuchRevision, e:
314
260
                pass
315
261
        raise e
316
262
 
317
 
    def get_revision_graph(self, revision_id):
318
 
        # we could probe incrementally until the pending
319
 
        # ghosts list stop growing, but its cheaper for now
320
 
        # to just ask for the complete graph for each repository.
321
 
        graphs = []
322
 
        for source in self._revision_sources:
323
 
            ghost_graph = source.get_revision_graph_with_ghosts()
324
 
            graphs.append(ghost_graph)
325
 
        absent = 0
326
 
        for graph in graphs:
327
 
            if not revision_id in graph.get_ancestors():
328
 
                absent += 1
329
 
        if absent == len(graphs):
330
 
            raise errors.NoSuchRevision(self._revision_sources[0], revision_id)
331
 
 
332
 
        # combine the graphs
333
 
        result = {}
334
 
        pending = set([revision_id])
335
 
        def find_parents(node_id):
336
 
            """find the parents for node_id."""
337
 
            for graph in graphs:
338
 
                ancestors = graph.get_ancestors()
339
 
                try:
340
 
                    return ancestors[node_id]
341
 
                except KeyError:
342
 
                    pass
343
 
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
344
 
        while len(pending):
345
 
            # all the graphs should have identical parent lists
346
 
            node_id = pending.pop()
347
 
            try:
348
 
                result[node_id] = find_parents(node_id)
349
 
                for parent_node in result[node_id]:
350
 
                    if not parent_node in result:
351
 
                        pending.add(parent_node)
352
 
            except errors.NoSuchRevision:
353
 
                # ghost, ignore it.
354
 
                pass
355
 
        return result
356
 
 
357
 
    def get_revision_graph_with_ghosts(self, revision_ids):
358
 
        # query all the sources for their entire graphs 
359
 
        # and then build a combined graph for just
360
 
        # revision_ids.
361
 
        graphs = []
362
 
        for source in self._revision_sources:
363
 
            ghost_graph = source.get_revision_graph_with_ghosts()
364
 
            graphs.append(ghost_graph.get_ancestors())
365
 
        for revision_id in revision_ids:
366
 
            absent = 0
367
 
            for graph in graphs:
368
 
                    if not revision_id in graph:
369
 
                        absent += 1
370
 
            if absent == len(graphs):
371
 
                raise errors.NoSuchRevision(self._revision_sources[0],
372
 
                                            revision_id)
373
 
 
374
 
        # combine the graphs
375
 
        result = Graph()
376
 
        pending = set(revision_ids)
377
 
        done = set()
378
 
        def find_parents(node_id):
379
 
            """find the parents for node_id."""
380
 
            for graph in graphs:
381
 
                try:
382
 
                    return graph[node_id]
383
 
                except KeyError:
384
 
                    pass
385
 
            raise errors.NoSuchRevision(self._revision_sources[0], node_id)
386
 
        while len(pending):
387
 
            # all the graphs should have identical parent lists
388
 
            node_id = pending.pop()
389
 
            try:
390
 
                parents = find_parents(node_id)
391
 
                for parent_node in parents:
392
 
                    # queued or done? 
393
 
                    if (parent_node not in pending and
394
 
                        parent_node not in done):
395
 
                        # no, queue
396
 
                        pending.add(parent_node)
397
 
                result.add_node(node_id, parents)
398
 
                done.add(node_id)
399
 
            except errors.NoSuchRevision:
400
 
                # ghost
401
 
                result.add_ghost(node_id)
402
 
                continue
403
 
        return result
404
 
 
405
 
    def lock_read(self):
406
 
        for source in self._revision_sources:
407
 
            source.lock_read()
408
 
 
409
 
    def unlock(self):
410
 
        for source in self._revision_sources:
411
 
            source.unlock()
412
 
 
413
 
 
414
 
@deprecated_function(zero_eight)
415
 
def get_intervening_revisions(ancestor_id, rev_id, rev_source,
 
263
def get_intervening_revisions(ancestor_id, rev_id, rev_source, 
416
264
                              revision_history=None):
417
265
    """Find the longest line of descent from maybe_ancestor to revision.
418
266
    Revision history is followed where possible.
423
271
    """
424
272
    root, ancestors, descendants = revision_graph(rev_id, rev_source)
425
273
    if len(descendants) == 0:
426
 
        raise errors.NoSuchRevision(rev_source, rev_id)
 
274
        raise NoSuchRevision(rev_source, rev_id)
427
275
    if ancestor_id not in descendants:
428
276
        rev_source.get_revision(ancestor_id)
429
 
        raise errors.NotAncestor(rev_id, ancestor_id)
 
277
        raise bzrlib.errors.NotAncestor(rev_id, ancestor_id)
430
278
    root_descendants = all_descendants(descendants, ancestor_id)
431
279
    root_descendants.add(ancestor_id)
432
280
    if rev_id not in root_descendants:
433
 
        raise errors.NotAncestor(rev_id, ancestor_id)
 
281
        raise bzrlib.errors.NotAncestor(rev_id, ancestor_id)
434
282
    distances = node_distances(descendants, ancestors, ancestor_id,
435
283
                               root_descendants=root_descendants)
436
284
 
454
302
        next = best_ancestor(next)
455
303
    path.reverse()
456
304
    return path
457
 
 
458
 
 
459
 
def is_reserved_id(revision_id):
460
 
    """Determine whether a revision id is reserved
461
 
 
462
 
    :return: True if the revision is is reserved, False otherwise
463
 
    """
464
 
    return isinstance(revision_id, basestring) and revision_id.endswith(':')
465
 
 
466
 
 
467
 
def check_not_reserved_id(revision_id):
468
 
    """Raise ReservedId if the supplied revision_id is reserved"""
469
 
    if is_reserved_id(revision_id):
470
 
        raise errors.ReservedId(revision_id)