~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Pool
  • Date: 2005-06-02 02:37:54 UTC
  • Revision ID: mbp@sourcefrog.net-20050602023754-fc3d4c02877ba29d
doc

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
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
 
 
18
 
import bisect
19
 
import datetime
20
 
import re
21
 
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    )
25
 
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
26
 
 
27
 
_marker = []
28
 
 
29
 
class RevisionInfo(object):
30
 
    """The results of applying a revision specification to a branch.
31
 
 
32
 
    An instance has two useful attributes: revno, and rev_id.
33
 
 
34
 
    They can also be accessed as spec[0] and spec[1] respectively,
35
 
    so that you can write code like:
36
 
    revno, rev_id = RevisionSpec(branch, spec)
37
 
    although this is probably going to be deprecated later.
38
 
 
39
 
    This class exists mostly to be the return value of a RevisionSpec,
40
 
    so that you can access the member you're interested in (number or id)
41
 
    or treat the result as a tuple.
42
 
    """
43
 
 
44
 
    def __init__(self, branch, revno, rev_id=_marker):
45
 
        self.branch = branch
46
 
        self.revno = revno
47
 
        if rev_id is _marker:
48
 
            # allow caller to be lazy
49
 
            if self.revno is None:
50
 
                self.rev_id = None
51
 
            else:
52
 
                self.rev_id = branch.get_rev_id(self.revno)
53
 
        else:
54
 
            self.rev_id = rev_id
55
 
 
56
 
    def __nonzero__(self):
57
 
        # first the easy ones...
58
 
        if self.rev_id is None:
59
 
            return False
60
 
        if self.revno is not None:
61
 
            return True
62
 
        # TODO: otherwise, it should depend on how I was built -
63
 
        # if it's in_history(branch), then check revision_history(),
64
 
        # if it's in_store(branch), do the check below
65
 
        return self.branch.repository.has_revision(self.rev_id)
66
 
 
67
 
    def __len__(self):
68
 
        return 2
69
 
 
70
 
    def __getitem__(self, index):
71
 
        if index == 0: return self.revno
72
 
        if index == 1: return self.rev_id
73
 
        raise IndexError(index)
74
 
 
75
 
    def get(self):
76
 
        return self.branch.repository.get_revision(self.rev_id)
77
 
 
78
 
    def __eq__(self, other):
79
 
        if type(other) not in (tuple, list, type(self)):
80
 
            return False
81
 
        if type(other) is type(self) and self.branch is not other.branch:
82
 
            return False
83
 
        return tuple(self) == tuple(other)
84
 
 
85
 
    def __repr__(self):
86
 
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
87
 
            self.revno, self.rev_id, self.branch)
88
 
 
89
 
# classes in this list should have a "prefix" attribute, against which
90
 
# string specs are matched
91
 
SPEC_TYPES = []
92
 
 
93
 
class RevisionSpec(object):
94
 
    """A parsed revision specification.
95
 
 
96
 
    A revision specification can be an integer, in which case it is
97
 
    assumed to be a revno (though this will translate negative values
98
 
    into positive ones); or it can be a string, in which case it is
99
 
    parsed for something like 'date:' or 'revid:' etc.
100
 
 
101
 
    Revision specs are an UI element, and they have been moved out
102
 
    of the branch class to leave "back-end" classes unaware of such
103
 
    details.  Code that gets a revno or rev_id from other code should
104
 
    not be using revision specs - revnos and revision ids are the
105
 
    accepted ways to refer to revisions internally.
106
 
 
107
 
    (Equivalent to the old Branch method get_revision_info())
108
 
    """
109
 
 
110
 
    prefix = None
111
 
 
112
 
    def __new__(cls, spec, foo=_marker):
113
 
        """Parse a revision specifier.
114
 
        """
115
 
        if spec is None:
116
 
            return object.__new__(RevisionSpec, spec)
117
 
 
118
 
        try:
119
 
            spec = int(spec)
120
 
        except ValueError:
121
 
            pass
122
 
 
123
 
        if isinstance(spec, int):
124
 
            return object.__new__(RevisionSpec_int, spec)
125
 
        elif isinstance(spec, basestring):
126
 
            for spectype in SPEC_TYPES:
127
 
                if spec.startswith(spectype.prefix):
128
 
                    return object.__new__(spectype, spec)
129
 
            else:
130
 
                raise BzrError('No namespace registered for string: %r' %
131
 
                               spec)
132
 
        else:
133
 
            raise TypeError('Unhandled revision type %s' % spec)
134
 
 
135
 
    def __init__(self, spec):
136
 
        if self.prefix and spec.startswith(self.prefix):
137
 
            spec = spec[len(self.prefix):]
138
 
        self.spec = spec
139
 
 
140
 
    def _match_on(self, branch, revs):
141
 
        return RevisionInfo(branch, 0, None)
142
 
 
143
 
    def _match_on_and_check(self, branch, revs):
144
 
        info = self._match_on(branch, revs)
145
 
        if info:
146
 
            return info
147
 
        elif info == (0, None):
148
 
            # special case - the empty tree
149
 
            return info
150
 
        elif self.prefix:
151
 
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
152
 
        else:
153
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
154
 
 
155
 
    def in_history(self, branch):
156
 
        if branch:
157
 
            revs = branch.revision_history()
158
 
        else:
159
 
            revs = None
160
 
        return self._match_on_and_check(branch, revs)
161
 
 
162
 
        # FIXME: in_history is somewhat broken,
163
 
        # it will return non-history revisions in many
164
 
        # circumstances. The expected facility is that
165
 
        # in_history only returns revision-history revs,
166
 
        # in_store returns any rev. RBC 20051010
167
 
    # aliases for now, when we fix the core logic, then they
168
 
    # will do what you expect.
169
 
    in_store = in_history
170
 
    in_branch = in_store
171
 
        
172
 
    def __repr__(self):
173
 
        # this is mostly for helping with testing
174
 
        return '<%s %s%s>' % (self.__class__.__name__,
175
 
                              self.prefix or '',
176
 
                              self.spec)
177
 
    
178
 
    def needs_branch(self):
179
 
        """Whether this revision spec needs a branch.
180
 
 
181
 
        Set this to False the branch argument of _match_on is not used.
182
 
        """
183
 
        return True
184
 
 
185
 
# private API
186
 
 
187
 
class RevisionSpec_int(RevisionSpec):
188
 
    """Spec is a number.  Special case."""
189
 
 
190
 
    def __init__(self, spec):
191
 
        self.spec = int(spec)
192
 
 
193
 
    def _match_on(self, branch, revs):
194
 
        if self.spec < 0:
195
 
            revno = len(revs) + self.spec + 1
196
 
        else:
197
 
            revno = self.spec
198
 
        try:
199
 
            rev_id = branch.get_rev_id(revno, revs)
200
 
        except NoSuchRevision:
201
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
202
 
        return RevisionInfo(branch, revno, rev_id)
203
 
 
204
 
 
205
 
class RevisionSpec_revno(RevisionSpec):
206
 
    prefix = 'revno:'
207
 
 
208
 
    def _match_on(self, branch, revs):
209
 
        """Lookup a revision by revision number"""
210
 
        loc = self.spec.find(':')
211
 
        if loc == -1:
212
 
            revno_spec = self.spec
213
 
            branch_spec = None
214
 
        else:
215
 
            revno_spec = self.spec[:loc]
216
 
            branch_spec = self.spec[loc+1:]
217
 
 
218
 
        if revno_spec == '':
219
 
            if not branch_spec:
220
 
                raise errors.InvalidRevisionSpec(self.prefix + self.spec,
221
 
                        branch, 'cannot have an empty revno and no branch')
222
 
            revno = None
223
 
        else:
224
 
            try:
225
 
                revno = int(revno_spec)
226
 
            except ValueError, e:
227
 
                raise errors.InvalidRevisionSpec(self.prefix + self.spec,
228
 
                                                 branch, e)
229
 
 
230
 
            if revno < 0:
231
 
                revno = len(revs) + revno + 1
232
 
 
233
 
        if branch_spec:
234
 
            from bzrlib.branch import Branch
235
 
            branch = Branch.open(branch_spec)
236
 
 
237
 
        try:
238
 
            revid = branch.get_rev_id(revno)
239
 
        except NoSuchRevision:
240
 
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
241
 
 
242
 
        return RevisionInfo(branch, revno)
243
 
        
244
 
    def needs_branch(self):
245
 
        return self.spec.find(':') == -1
246
 
 
247
 
SPEC_TYPES.append(RevisionSpec_revno)
248
 
 
249
 
 
250
 
class RevisionSpec_revid(RevisionSpec):
251
 
    prefix = 'revid:'
252
 
 
253
 
    def _match_on(self, branch, revs):
254
 
        try:
255
 
            revno = revs.index(self.spec) + 1
256
 
        except ValueError:
257
 
            revno = None
258
 
        return RevisionInfo(branch, revno, self.spec)
259
 
 
260
 
SPEC_TYPES.append(RevisionSpec_revid)
261
 
 
262
 
 
263
 
class RevisionSpec_last(RevisionSpec):
264
 
 
265
 
    prefix = 'last:'
266
 
 
267
 
    def _match_on(self, branch, revs):
268
 
        if self.spec == '':
269
 
            if not revs:
270
 
                raise NoCommits(branch)
271
 
            return RevisionInfo(branch, len(revs), revs[-1])
272
 
 
273
 
        try:
274
 
            offset = int(self.spec)
275
 
        except ValueError, e:
276
 
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch, e)
277
 
 
278
 
        if offset <= 0:
279
 
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch,
280
 
                                             'you must supply a positive value')
281
 
        revno = len(revs) - offset + 1
282
 
        try:
283
 
            revision_id = branch.get_rev_id(revno, revs)
284
 
        except errors.NoSuchRevision:
285
 
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
286
 
        return RevisionInfo(branch, revno, revision_id)
287
 
 
288
 
SPEC_TYPES.append(RevisionSpec_last)
289
 
 
290
 
 
291
 
class RevisionSpec_before(RevisionSpec):
292
 
 
293
 
    prefix = 'before:'
294
 
    
295
 
    def _match_on(self, branch, revs):
296
 
        r = RevisionSpec(self.spec)._match_on(branch, revs)
297
 
        if (r.revno is None) or (r.revno == 0):
298
 
            return r
299
 
        return RevisionInfo(branch, r.revno - 1)
300
 
 
301
 
SPEC_TYPES.append(RevisionSpec_before)
302
 
 
303
 
 
304
 
class RevisionSpec_tag(RevisionSpec):
305
 
    prefix = 'tag:'
306
 
 
307
 
    def _match_on(self, branch, revs):
308
 
        raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch,
309
 
                                         'tag: namespace registered,'
310
 
                                         ' but not implemented')
311
 
 
312
 
SPEC_TYPES.append(RevisionSpec_tag)
313
 
 
314
 
 
315
 
class RevisionSpec_revs:
316
 
    def __init__(self, revs, branch):
317
 
        self.revs = revs
318
 
        self.branch = branch
319
 
    def __getitem__(self, index):
320
 
        r = self.branch.repository.get_revision(self.revs[index])
321
 
        # TODO: Handle timezone.
322
 
        return datetime.datetime.fromtimestamp(r.timestamp)
323
 
    def __len__(self):
324
 
        return len(self.revs)
325
 
 
326
 
 
327
 
class RevisionSpec_date(RevisionSpec):
328
 
    prefix = 'date:'
329
 
    _date_re = re.compile(
330
 
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
331
 
            r'(,|T)?\s*'
332
 
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
333
 
        )
334
 
 
335
 
    def _match_on(self, branch, revs):
336
 
        """
337
 
        Spec for date revisions:
338
 
          date:value
339
 
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
340
 
          matches the first entry after a given date (either at midnight or
341
 
          at a specified time).
342
 
 
343
 
          So the proper way of saying 'give me all entries for today' is:
344
 
              -r date:yesterday..date:today
345
 
        """
346
 
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
347
 
        if self.spec.lower() == 'yesterday':
348
 
            dt = today - datetime.timedelta(days=1)
349
 
        elif self.spec.lower() == 'today':
350
 
            dt = today
351
 
        elif self.spec.lower() == 'tomorrow':
352
 
            dt = today + datetime.timedelta(days=1)
353
 
        else:
354
 
            m = self._date_re.match(self.spec)
355
 
            if not m or (not m.group('date') and not m.group('time')):
356
 
                raise BzrError('Invalid revision date %r' % self.spec)
357
 
 
358
 
            if m.group('date'):
359
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
360
 
            else:
361
 
                year, month, day = today.year, today.month, today.day
362
 
            if m.group('time'):
363
 
                hour = int(m.group('hour'))
364
 
                minute = int(m.group('minute'))
365
 
                if m.group('second'):
366
 
                    second = int(m.group('second'))
367
 
                else:
368
 
                    second = 0
369
 
            else:
370
 
                hour, minute, second = 0,0,0
371
 
 
372
 
            dt = datetime.datetime(year=year, month=month, day=day,
373
 
                    hour=hour, minute=minute, second=second)
374
 
        branch.lock_read()
375
 
        try:
376
 
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
377
 
        finally:
378
 
            branch.unlock()
379
 
        if rev == len(revs):
380
 
            return RevisionInfo(branch, None)
381
 
        else:
382
 
            return RevisionInfo(branch, rev + 1)
383
 
 
384
 
SPEC_TYPES.append(RevisionSpec_date)
385
 
 
386
 
 
387
 
class RevisionSpec_ancestor(RevisionSpec):
388
 
    prefix = 'ancestor:'
389
 
 
390
 
    def _match_on(self, branch, revs):
391
 
        from branch import Branch
392
 
        from revision import common_ancestor, MultipleRevisionSources
393
 
        other_branch = Branch.open_containing(self.spec)[0]
394
 
        revision_a = branch.last_revision()
395
 
        revision_b = other_branch.last_revision()
396
 
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
397
 
            if r is None:
398
 
                raise NoCommits(b)
399
 
        revision_source = MultipleRevisionSources(branch.repository,
400
 
                                                  other_branch.repository)
401
 
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
402
 
        try:
403
 
            revno = branch.revision_id_to_revno(rev_id)
404
 
        except NoSuchRevision:
405
 
            revno = None
406
 
        return RevisionInfo(branch, revno, rev_id)
407
 
        
408
 
SPEC_TYPES.append(RevisionSpec_ancestor)
409
 
 
410
 
class RevisionSpec_branch(RevisionSpec):
411
 
    """A branch: revision specifier.
412
 
 
413
 
    This takes the path to a branch and returns its tip revision id.
414
 
    """
415
 
    prefix = 'branch:'
416
 
 
417
 
    def _match_on(self, branch, revs):
418
 
        from branch import Branch
419
 
        other_branch = Branch.open_containing(self.spec)[0]
420
 
        revision_b = other_branch.last_revision()
421
 
        if revision_b is None:
422
 
            raise NoCommits(other_branch)
423
 
        # pull in the remote revisions so we can diff
424
 
        branch.fetch(other_branch, revision_b)
425
 
        try:
426
 
            revno = branch.revision_id_to_revno(revision_b)
427
 
        except NoSuchRevision:
428
 
            revno = None
429
 
        return RevisionInfo(branch, revno, revision_b)
430
 
        
431
 
SPEC_TYPES.append(RevisionSpec_branch)