~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revision.py

  • Committer: Martin Pool
  • Date: 2005-06-22 06:38:18 UTC
  • Revision ID: mbp@sourcefrog.net-20050622063818-cd8d21b14bd4b636
- add plugin patch, still being integrated

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
 
from bzrlib.lazy_import import lazy_import
22
 
lazy_import(globals(), """
23
 
from bzrlib import bugtracker
24
 
""")
25
 
from bzrlib import (
26
 
    errors,
27
 
    symbol_versioning,
28
 
    )
29
 
from bzrlib.osutils import contains_whitespace
30
 
 
31
 
NULL_REVISION="null:"
32
 
CURRENT_REVISION="current:"
33
 
 
34
 
 
35
 
class Revision(object):
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
 
 
19
 
 
20
from xml import XMLMixin
 
21
 
 
22
try:
 
23
    from cElementTree import Element, ElementTree, SubElement
 
24
except ImportError:
 
25
    from elementtree.ElementTree import Element, ElementTree, SubElement
 
26
 
 
27
from errors import BzrError
 
28
 
 
29
 
 
30
class RevisionReference:
 
31
    """
 
32
    Reference to a stored revision.
 
33
 
 
34
    Includes the revision_id and revision_sha1.
 
35
    """
 
36
    revision_id = None
 
37
    revision_sha1 = None
 
38
    def __init__(self, revision_id, revision_sha1):
 
39
        if revision_id == None \
 
40
           or isinstance(revision_id, basestring):
 
41
            self.revision_id = revision_id
 
42
        else:
 
43
            raise ValueError('bad revision_id %r' % revision_id)
 
44
 
 
45
        if revision_sha1 != None:
 
46
            if isinstance(revision_sha1, basestring) \
 
47
               and len(revision_sha1) == 40:
 
48
                self.revision_sha1 = revision_sha1
 
49
            else:
 
50
                raise ValueError('bad revision_sha1 %r' % revision_sha1)
 
51
                
 
52
 
 
53
 
 
54
class Revision(XMLMixin):
36
55
    """Single revision on a branch.
37
56
 
38
57
    Revisions may know their revision_hash, but only once they've been
40
59
    into the file it describes.
41
60
 
42
61
    After bzr 0.0.5 revisions are allowed to have multiple parents.
43
 
 
44
 
    parent_ids
45
 
        List of parent revision_ids
46
 
 
47
 
    properties
48
 
        Dictionary of revision properties.  These are attached to the
49
 
        revision as extra metadata.  The name must be a single
50
 
        word; the value can be an arbitrary string.
 
62
    To support old clients this is written out in a slightly redundant
 
63
    form: the first parent as the predecessor.  This will eventually
 
64
    be dropped.
 
65
 
 
66
    parents
 
67
        List of parent revisions, each is a RevisionReference.
51
68
    """
52
 
 
53
 
    def __init__(self, revision_id, properties=None, **args):
54
 
        self.revision_id = revision_id
55
 
        if properties is None:
56
 
            self.properties = {}
57
 
        else:
58
 
            self.properties = properties
59
 
            self._check_properties()
60
 
        self.committer = None
61
 
        self.parent_ids = []
62
 
        self.parent_sha1s = []
63
 
        """Not used anymore - legacy from for 4."""
 
69
    inventory_id = None
 
70
    inventory_sha1 = None
 
71
    revision_id = None
 
72
    timestamp = None
 
73
    message = None
 
74
    timezone = None
 
75
    committer = None
 
76
    
 
77
    def __init__(self, **args):
64
78
        self.__dict__.update(args)
 
79
        self.parents = []
 
80
 
 
81
    def _get_precursor(self):
 
82
        from warnings import warn
 
83
        warn("Revision.precursor is deprecated", stacklevel=2)
 
84
        if self.parents:
 
85
            return self.parents[0].revision_id
 
86
        else:
 
87
            return None
 
88
 
 
89
 
 
90
    def _get_precursor_sha1(self):
 
91
        from warnings import warn
 
92
        warn("Revision.precursor_sha1 is deprecated", stacklevel=2)
 
93
        if self.parents:
 
94
            return self.parents[0].revision_sha1
 
95
        else:
 
96
            return None    
 
97
 
 
98
 
 
99
    def _fail(self):
 
100
        raise Exception("can't assign to precursor anymore")
 
101
 
 
102
 
 
103
    precursor = property(_get_precursor, _fail, _fail)
 
104
    precursor_sha1 = property(_get_precursor_sha1, _fail, _fail)
 
105
 
 
106
 
65
107
 
66
108
    def __repr__(self):
67
109
        return "<Revision id %s>" % self.revision_id
68
110
 
69
 
    def __eq__(self, other):
70
 
        if not isinstance(other, Revision):
71
 
            return False
72
 
        return (
73
 
                self.inventory_sha1 == other.inventory_sha1
74
 
                and self.revision_id == other.revision_id
75
 
                and self.timestamp == other.timestamp
76
 
                and self.message == other.message
77
 
                and self.timezone == other.timezone
78
 
                and self.committer == other.committer
79
 
                and self.properties == other.properties
80
 
                and self.parent_ids == other.parent_ids)
81
 
 
82
 
    def __ne__(self, other):
83
 
        return not self.__eq__(other)
84
 
 
85
 
    def _check_properties(self):
86
 
        """Verify that all revision properties are OK."""
87
 
        for name, value in self.properties.iteritems():
88
 
            if not isinstance(name, basestring) or contains_whitespace(name):
89
 
                raise ValueError("invalid property name %r" % name)
90
 
            if not isinstance(value, basestring):
91
 
                raise ValueError("invalid property value %r for %r" %
92
 
                                 (value, name))
93
 
 
94
 
    def get_history(self, repository):
95
 
        """Return the canonical line-of-history for this revision.
96
 
 
97
 
        If ghosts are present this may differ in result from a ghost-free
98
 
        repository.
99
 
        """
100
 
        current_revision = self
101
 
        reversed_result = []
102
 
        while current_revision is not None:
103
 
            reversed_result.append(current_revision.revision_id)
104
 
            if not len (current_revision.parent_ids):
105
 
                reversed_result.append(None)
106
 
                current_revision = None
107
 
            else:
108
 
                next_revision_id = current_revision.parent_ids[0]
109
 
                current_revision = repository.get_revision(next_revision_id)
110
 
        reversed_result.reverse()
111
 
        return reversed_result
112
 
 
113
 
    def get_summary(self):
114
 
        """Get the first line of the log message for this revision.
115
 
 
116
 
        Return an empty string if message is None.
117
 
        """
118
 
        if self.message:
119
 
            return self.message.lstrip().split('\n', 1)[0]
120
 
        else:
121
 
            return ''
122
 
 
123
 
    def get_apparent_authors(self):
124
 
        """Return the apparent authors of this revision.
125
 
 
126
 
        If the revision properties contain the names of the authors,
127
 
        return them. Otherwise return the committer name.
128
 
 
129
 
        The return value will be a list containing at least one element.
130
 
        """
131
 
        authors = self.properties.get('authors', None)
132
 
        if authors is None:
133
 
            author = self.properties.get('author', self.committer)
134
 
            if author is None:
135
 
                return []
136
 
            return [author]
137
 
        else:
138
 
            return authors.split("\n")
139
 
 
140
 
    def iter_bugs(self):
141
 
        """Iterate over the bugs associated with this revision."""
142
 
        bug_property = self.properties.get('bugs', None)
143
 
        if bug_property is None:
144
 
            return
145
 
        for line in bug_property.splitlines():
146
 
            try:
147
 
                url, status = line.split(None, 2)
148
 
            except ValueError:
149
 
                raise errors.InvalidLineInBugsProperty(line)
150
 
            if status not in bugtracker.ALLOWED_BUG_STATUSES:
151
 
                raise errors.InvalidBugStatus(status)
152
 
            yield url, status
153
 
 
154
 
 
155
 
def iter_ancestors(revision_id, revision_source, only_present=False):
156
 
    ancestors = (revision_id,)
157
 
    distance = 0
158
 
    while len(ancestors) > 0:
159
 
        new_ancestors = []
160
 
        for ancestor in ancestors:
161
 
            if not only_present:
162
 
                yield ancestor, distance
163
 
            try:
164
 
                revision = revision_source.get_revision(ancestor)
165
 
            except errors.NoSuchRevision, e:
166
 
                if e.revision == revision_id:
167
 
                    raise
168
 
                else:
169
 
                    continue
170
 
            if only_present:
171
 
                yield ancestor, distance
172
 
            new_ancestors.extend(revision.parent_ids)
173
 
        ancestors = new_ancestors
174
 
        distance += 1
175
 
 
176
 
 
177
 
def find_present_ancestors(revision_id, revision_source):
178
 
    """Return the ancestors of a revision present in a branch.
179
 
 
180
 
    It's possible that a branch won't have the complete ancestry of
181
 
    one of its revisions.
182
 
 
183
 
    """
184
 
    found_ancestors = {}
185
 
    anc_iter = enumerate(iter_ancestors(revision_id, revision_source,
186
 
                         only_present=True))
187
 
    for anc_order, (anc_id, anc_distance) in anc_iter:
188
 
        if anc_id not in found_ancestors:
189
 
            found_ancestors[anc_id] = (anc_order, anc_distance)
190
 
    return found_ancestors
191
 
 
192
 
 
193
 
def __get_closest(intersection):
194
 
    intersection.sort()
195
 
    matches = []
196
 
    for entry in intersection:
197
 
        if entry[0] == intersection[0][0]:
198
 
            matches.append(entry[2])
199
 
    return matches
200
 
 
201
 
 
202
 
def is_reserved_id(revision_id):
203
 
    """Determine whether a revision id is reserved
204
 
 
205
 
    :return: True if the revision is reserved, False otherwise
206
 
    """
207
 
    return isinstance(revision_id, basestring) and revision_id.endswith(':')
208
 
 
209
 
 
210
 
def check_not_reserved_id(revision_id):
211
 
    """Raise ReservedId if the supplied revision_id is reserved"""
212
 
    if is_reserved_id(revision_id):
213
 
        raise errors.ReservedId(revision_id)
214
 
 
215
 
 
216
 
def ensure_null(revision_id):
217
 
    """Ensure only NULL_REVISION is used to represent the null revision"""
218
 
    if revision_id is None:
219
 
        symbol_versioning.warn('NULL_REVISION should be used for the null'
220
 
            ' revision instead of None, as of bzr 0.91.',
221
 
            DeprecationWarning, stacklevel=2)
222
 
        return NULL_REVISION
223
 
    else:
224
 
        return revision_id
225
 
 
226
 
 
227
 
def is_null(revision_id):
228
 
    if revision_id is None:
229
 
        symbol_versioning.warn('NULL_REVISION should be used for the null'
230
 
            ' revision instead of None, as of bzr 0.90.',
231
 
            DeprecationWarning, stacklevel=2)
232
 
    return revision_id in (None, NULL_REVISION)
 
111
        
 
112
    def to_element(self):
 
113
        root = Element('revision',
 
114
                       committer = self.committer,
 
115
                       timestamp = '%.9f' % self.timestamp,
 
116
                       revision_id = self.revision_id,
 
117
                       inventory_id = self.inventory_id,
 
118
                       inventory_sha1 = self.inventory_sha1,
 
119
                       )
 
120
        if self.timezone:
 
121
            root.set('timezone', str(self.timezone))
 
122
        root.text = '\n'
 
123
        
 
124
        msg = SubElement(root, 'message')
 
125
        msg.text = self.message
 
126
        msg.tail = '\n'
 
127
 
 
128
        if self.parents:
 
129
            # first parent stored as precursor for compatability with 0.0.5 and
 
130
            # earlier
 
131
            pr = self.parents[0]
 
132
            assert pr.revision_id
 
133
            root.set('precursor', pr.revision_id)
 
134
            if pr.revision_sha1:
 
135
                root.set('precursor_sha1', pr.revision_sha1)
 
136
                
 
137
        if self.parents:
 
138
            pelts = SubElement(root, 'parents')
 
139
            pelts.tail = pelts.text = '\n'
 
140
            for rr in self.parents:
 
141
                assert isinstance(rr, RevisionReference)
 
142
                p = SubElement(pelts, 'revision_ref')
 
143
                p.tail = '\n'
 
144
                assert rr.revision_id
 
145
                p.set('revision_id', rr.revision_id)
 
146
                if rr.revision_sha1:
 
147
                    p.set('revision_sha1', rr.revision_sha1)
 
148
 
 
149
        return root
 
150
 
 
151
 
 
152
    def from_element(cls, elt):
 
153
        return unpack_revision(elt)
 
154
 
 
155
    from_element = classmethod(from_element)
 
156
 
 
157
 
 
158
 
 
159
def unpack_revision(elt):
 
160
    """Convert XML element into Revision object."""
 
161
    # <changeset> is deprecated...
 
162
    if elt.tag not in ('revision', 'changeset'):
 
163
        raise BzrError("unexpected tag in revision file: %r" % elt)
 
164
 
 
165
    rev = Revision(committer = elt.get('committer'),
 
166
                   timestamp = float(elt.get('timestamp')),
 
167
                   revision_id = elt.get('revision_id'),
 
168
                   inventory_id = elt.get('inventory_id'),
 
169
                   inventory_sha1 = elt.get('inventory_sha1')
 
170
                   )
 
171
 
 
172
    precursor = elt.get('precursor')
 
173
    precursor_sha1 = elt.get('precursor_sha1')
 
174
 
 
175
    pelts = elt.find('parents')
 
176
 
 
177
    if precursor:
 
178
        # revisions written prior to 0.0.5 have a single precursor
 
179
        # give as an attribute
 
180
        rev_ref = RevisionReference(precursor, precursor_sha1)
 
181
        rev.parents.append(rev_ref)
 
182
    elif pelts:
 
183
        for p in pelts:
 
184
            assert p.tag == 'revision_ref', \
 
185
                   "bad parent node tag %r" % p.tag
 
186
            rev_ref = RevisionReference(p.get('revision_id'),
 
187
                                        p.get('revision_sha1'))
 
188
            rev.parents.append(rev_ref)
 
189
 
 
190
    v = elt.get('timezone')
 
191
    rev.timezone = v and int(v)
 
192
 
 
193
    rev.message = elt.findtext('message') # text of <message>
 
194
    return rev