/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/revisionspec.py

merge

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