/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

  • Committer: Martin Pool
  • Date: 2006-10-06 02:04:17 UTC
  • mfrom: (1908.10.1 bench_usecases.merge2)
  • mto: This revision was merged to the branch mainline in revision 2068.
  • Revision ID: mbp@sourcefrog.net-20061006020417-4949ca86f4417a4d
merge additional fix from cfbolz

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Canonical Ltd
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
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
17
 
 
18
import bisect
18
19
import datetime
19
20
import re
20
 
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
 
21
 
 
22
from bzrlib import (
 
23
    errors,
 
24
    revision,
 
25
    symbol_versioning,
 
26
    trace,
 
27
    )
 
28
 
21
29
 
22
30
_marker = []
23
31
 
 
32
 
24
33
class RevisionInfo(object):
25
34
    """The results of applying a revision specification to a branch.
26
35
 
81
90
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
82
91
            self.revno, self.rev_id, self.branch)
83
92
 
 
93
 
84
94
# classes in this list should have a "prefix" attribute, against which
85
95
# string specs are matched
86
96
SPEC_TYPES = []
 
97
_revno_regex = None
 
98
 
87
99
 
88
100
class RevisionSpec(object):
89
101
    """A parsed revision specification.
104
116
 
105
117
    prefix = None
106
118
 
107
 
    def __new__(cls, spec, foo=_marker):
108
 
        """Parse a revision specifier.
 
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.
109
137
        """
 
138
        if not isinstance(spec, (type(None), basestring)):
 
139
            raise TypeError('error')
 
140
 
110
141
        if spec is None:
111
 
            return object.__new__(RevisionSpec, spec)
112
 
 
113
 
        try:
114
 
            spec = int(spec)
115
 
        except ValueError:
116
 
            pass
117
 
 
118
 
        if isinstance(spec, int):
119
 
            return object.__new__(RevisionSpec_int, spec)
120
 
        elif isinstance(spec, basestring):
121
 
            for spectype in SPEC_TYPES:
122
 
                if spec.startswith(spectype.prefix):
123
 
                    return object.__new__(spectype, spec)
124
 
            else:
125
 
                raise BzrError('No namespace registered for string: %r' %
126
 
                               spec)
 
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)
127
152
        else:
128
 
            raise TypeError('Unhandled revision type %s' % spec)
129
 
 
130
 
    def __init__(self, spec):
 
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
131
178
        if self.prefix and spec.startswith(self.prefix):
132
179
            spec = spec[len(self.prefix):]
133
180
        self.spec = spec
134
181
 
135
182
    def _match_on(self, branch, revs):
 
183
        trace.mutter('Returning RevisionSpec._match_on: None')
136
184
        return RevisionInfo(branch, 0, None)
137
185
 
138
186
    def _match_on_and_check(self, branch, revs):
143
191
            # special case - the empty tree
144
192
            return info
145
193
        elif self.prefix:
146
 
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
 
194
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
147
195
        else:
148
 
            raise NoSuchRevision(branch, str(self.spec))
 
196
            raise errors.InvalidRevisionSpec(self.spec, branch)
149
197
 
150
198
    def in_history(self, branch):
151
 
        revs = branch.revision_history()
 
199
        if branch:
 
200
            revs = branch.revision_history()
 
201
        else:
 
202
            revs = None
152
203
        return self._match_on_and_check(branch, revs)
153
204
 
154
205
        # FIXME: in_history is somewhat broken,
163
214
        
164
215
    def __repr__(self):
165
216
        # this is mostly for helping with testing
166
 
        return '<%s %s%s>' % (self.__class__.__name__,
167
 
                              self.prefix or '',
168
 
                              self.spec)
 
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
169
233
 
170
234
 
171
235
# private API
172
236
 
173
 
class RevisionSpec_int(RevisionSpec):
174
 
    """Spec is a number.  Special case."""
175
 
    def __init__(self, spec):
176
 
        self.spec = int(spec)
177
 
 
178
 
    def _match_on(self, branch, revs):
179
 
        if self.spec < 0:
180
 
            revno = len(revs) + self.spec + 1
181
 
        else:
182
 
            revno = self.spec
183
 
        rev_id = branch.get_rev_id(revno, revs)
184
 
        return RevisionInfo(branch, revno, rev_id)
185
 
 
186
 
 
187
237
class RevisionSpec_revno(RevisionSpec):
188
238
    prefix = 'revno:'
189
239
 
190
240
    def _match_on(self, branch, revs):
191
241
        """Lookup a revision by revision number"""
 
242
        loc = self.spec.find(':')
 
243
        if loc == -1:
 
244
            revno_spec = self.spec
 
245
            branch_spec = None
 
246
        else:
 
247
            revno_spec = self.spec[:loc]
 
248
            branch_spec = self.spec[loc+1:]
 
249
 
 
250
        if revno_spec == '':
 
251
            if not branch_spec:
 
252
                raise errors.InvalidRevisionSpec(self.user_spec,
 
253
                        branch, 'cannot have an empty revno and no branch')
 
254
            revno = None
 
255
        else:
 
256
            try:
 
257
                revno = int(revno_spec)
 
258
            except ValueError, e:
 
259
                raise errors.InvalidRevisionSpec(self.user_spec,
 
260
                                                 branch, e)
 
261
 
 
262
        if branch_spec:
 
263
            from bzrlib.branch import Branch
 
264
            branch = Branch.open(branch_spec)
 
265
            # Need to use a new revision history
 
266
            # because we are using a specific branch
 
267
            revs = branch.revision_history()
 
268
 
 
269
        if revno < 0:
 
270
            if (-revno) >= len(revs):
 
271
                revno = 1
 
272
            else:
 
273
                revno = len(revs) + revno + 1
192
274
        try:
193
 
            return RevisionInfo(branch, int(self.spec))
194
 
        except ValueError:
195
 
            return RevisionInfo(branch, None)
 
275
            revision_id = branch.get_rev_id(revno, revs)
 
276
        except errors.NoSuchRevision:
 
277
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
278
        return RevisionInfo(branch, revno, revision_id)
 
279
        
 
280
    def needs_branch(self):
 
281
        return self.spec.find(':') == -1
 
282
 
 
283
    def get_branch(self):
 
284
        if self.spec.find(':') == -1:
 
285
            return None
 
286
        else:
 
287
            return self.spec[self.spec.find(':')+1:]
 
288
 
 
289
# Old compatibility 
 
290
RevisionSpec_int = RevisionSpec_revno
196
291
 
197
292
SPEC_TYPES.append(RevisionSpec_revno)
198
293
 
202
297
 
203
298
    def _match_on(self, branch, revs):
204
299
        try:
205
 
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
 
300
            revno = revs.index(self.spec) + 1
206
301
        except ValueError:
207
 
            return RevisionInfo(branch, None, self.spec)
 
302
            revno = None
 
303
        return RevisionInfo(branch, revno, self.spec)
208
304
 
209
305
SPEC_TYPES.append(RevisionSpec_revid)
210
306
 
214
310
    prefix = 'last:'
215
311
 
216
312
    def _match_on(self, branch, revs):
 
313
        if self.spec == '':
 
314
            if not revs:
 
315
                raise errors.NoCommits(branch)
 
316
            return RevisionInfo(branch, len(revs), revs[-1])
 
317
 
217
318
        try:
218
319
            offset = int(self.spec)
219
 
        except ValueError:
220
 
            return RevisionInfo(branch, None)
221
 
        else:
222
 
            if offset <= 0:
223
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
224
 
            return RevisionInfo(branch, len(revs) - offset + 1)
 
320
        except ValueError, e:
 
321
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
322
 
 
323
        if offset <= 0:
 
324
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
325
                                             'you must supply a positive value')
 
326
        revno = len(revs) - offset + 1
 
327
        try:
 
328
            revision_id = branch.get_rev_id(revno, revs)
 
329
        except errors.NoSuchRevision:
 
330
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
331
        return RevisionInfo(branch, revno, revision_id)
225
332
 
226
333
SPEC_TYPES.append(RevisionSpec_last)
227
334
 
231
338
    prefix = 'before:'
232
339
    
233
340
    def _match_on(self, branch, revs):
234
 
        r = RevisionSpec(self.spec)._match_on(branch, revs)
235
 
        if (r.revno is None) or (r.revno == 0):
236
 
            return r
237
 
        return RevisionInfo(branch, r.revno - 1)
 
341
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
 
342
        if r.revno == 0:
 
343
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
344
                                         'cannot go before the null: revision')
 
345
        if r.revno is None:
 
346
            # We need to use the repository history here
 
347
            rev = branch.repository.get_revision(r.rev_id)
 
348
            if not rev.parent_ids:
 
349
                revno = 0
 
350
                revision_id = None
 
351
            else:
 
352
                revision_id = rev.parent_ids[0]
 
353
                try:
 
354
                    revno = revs.index(revision_id) + 1
 
355
                except ValueError:
 
356
                    revno = None
 
357
        else:
 
358
            revno = r.revno - 1
 
359
            try:
 
360
                revision_id = branch.get_rev_id(revno, revs)
 
361
            except errors.NoSuchRevision:
 
362
                raise errors.InvalidRevisionSpec(self.user_spec,
 
363
                                                 branch)
 
364
        return RevisionInfo(branch, revno, revision_id)
238
365
 
239
366
SPEC_TYPES.append(RevisionSpec_before)
240
367
 
243
370
    prefix = 'tag:'
244
371
 
245
372
    def _match_on(self, branch, revs):
246
 
        raise BzrError('tag: namespace registered, but not implemented.')
 
373
        raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
374
                                         'tag: namespace registered,'
 
375
                                         ' but not implemented')
247
376
 
248
377
SPEC_TYPES.append(RevisionSpec_tag)
249
378
 
250
379
 
 
380
class _RevListToTimestamps(object):
 
381
    """This takes a list of revisions, and allows you to bisect by date"""
 
382
 
 
383
    __slots__ = ['revs', 'branch']
 
384
 
 
385
    def __init__(self, revs, branch):
 
386
        self.revs = revs
 
387
        self.branch = branch
 
388
 
 
389
    def __getitem__(self, index):
 
390
        """Get the date of the index'd item"""
 
391
        r = self.branch.repository.get_revision(self.revs[index])
 
392
        # TODO: Handle timezone.
 
393
        return datetime.datetime.fromtimestamp(r.timestamp)
 
394
 
 
395
    def __len__(self):
 
396
        return len(self.revs)
 
397
 
 
398
 
251
399
class RevisionSpec_date(RevisionSpec):
252
400
    prefix = 'date:'
253
401
    _date_re = re.compile(
265
413
          at a specified time).
266
414
 
267
415
          So the proper way of saying 'give me all entries for today' is:
268
 
              -r date:today..date:tomorrow
 
416
              -r date:yesterday..date:today
269
417
        """
270
418
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
271
419
        if self.spec.lower() == 'yesterday':
277
425
        else:
278
426
            m = self._date_re.match(self.spec)
279
427
            if not m or (not m.group('date') and not m.group('time')):
280
 
                raise BzrError('Invalid revision date %r' % self.spec)
281
 
 
282
 
            if m.group('date'):
283
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
284
 
            else:
285
 
                year, month, day = today.year, today.month, today.day
286
 
            if m.group('time'):
287
 
                hour = int(m.group('hour'))
288
 
                minute = int(m.group('minute'))
289
 
                if m.group('second'):
290
 
                    second = int(m.group('second'))
291
 
                else:
292
 
                    second = 0
293
 
            else:
294
 
                hour, minute, second = 0,0,0
 
428
                raise errors.InvalidRevisionSpec(self.user_spec,
 
429
                                                 branch, 'invalid date')
 
430
 
 
431
            try:
 
432
                if m.group('date'):
 
433
                    year = int(m.group('year'))
 
434
                    month = int(m.group('month'))
 
435
                    day = int(m.group('day'))
 
436
                else:
 
437
                    year = today.year
 
438
                    month = today.month
 
439
                    day = today.day
 
440
 
 
441
                if m.group('time'):
 
442
                    hour = int(m.group('hour'))
 
443
                    minute = int(m.group('minute'))
 
444
                    if m.group('second'):
 
445
                        second = int(m.group('second'))
 
446
                    else:
 
447
                        second = 0
 
448
                else:
 
449
                    hour, minute, second = 0,0,0
 
450
            except ValueError:
 
451
                raise errors.InvalidRevisionSpec(self.user_spec,
 
452
                                                 branch, 'invalid date')
295
453
 
296
454
            dt = datetime.datetime(year=year, month=month, day=day,
297
455
                    hour=hour, minute=minute, second=second)
298
 
        first = dt
299
 
        for i in range(len(revs)):
300
 
            r = branch.repository.get_revision(revs[i])
301
 
            # TODO: Handle timezone.
302
 
            dt = datetime.datetime.fromtimestamp(r.timestamp)
303
 
            if first <= dt:
304
 
                return RevisionInfo(branch, i+1)
305
 
        return RevisionInfo(branch, None)
 
456
        branch.lock_read()
 
457
        try:
 
458
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
459
        finally:
 
460
            branch.unlock()
 
461
        if rev == len(revs):
 
462
            return RevisionInfo(branch, None)
 
463
        else:
 
464
            return RevisionInfo(branch, rev + 1)
306
465
 
307
466
SPEC_TYPES.append(RevisionSpec_date)
308
467
 
311
470
    prefix = 'ancestor:'
312
471
 
313
472
    def _match_on(self, branch, revs):
314
 
        from branch import Branch
315
 
        from revision import common_ancestor, MultipleRevisionSources
316
 
        other_branch = Branch.open_containing(self.spec)[0]
 
473
        from bzrlib.branch import Branch
 
474
 
 
475
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
476
        other_branch = Branch.open(self.spec)
317
477
        revision_a = branch.last_revision()
318
478
        revision_b = other_branch.last_revision()
319
479
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
320
 
            if r is None:
321
 
                raise NoCommits(b)
322
 
        revision_source = MultipleRevisionSources(branch.repository,
323
 
                                                  other_branch.repository)
324
 
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
 
480
            if r in (None, revision.NULL_REVISION):
 
481
                raise errors.NoCommits(b)
 
482
        revision_source = revision.MultipleRevisionSources(
 
483
                branch.repository, other_branch.repository)
 
484
        rev_id = revision.common_ancestor(revision_a, revision_b,
 
485
                                          revision_source)
325
486
        try:
326
487
            revno = branch.revision_id_to_revno(rev_id)
327
 
        except NoSuchRevision:
 
488
        except errors.NoSuchRevision:
328
489
            revno = None
329
490
        return RevisionInfo(branch, revno, rev_id)
330
491
        
331
492
SPEC_TYPES.append(RevisionSpec_ancestor)
332
493
 
 
494
 
333
495
class RevisionSpec_branch(RevisionSpec):
334
496
    """A branch: revision specifier.
335
497
 
338
500
    prefix = 'branch:'
339
501
 
340
502
    def _match_on(self, branch, revs):
341
 
        from branch import Branch
342
 
        other_branch = Branch.open_containing(self.spec)[0]
 
503
        from bzrlib.branch import Branch
 
504
        other_branch = Branch.open(self.spec)
343
505
        revision_b = other_branch.last_revision()
344
 
        if revision_b is None:
345
 
            raise NoCommits(other_branch)
 
506
        if revision_b in (None, revision.NULL_REVISION):
 
507
            raise errors.NoCommits(other_branch)
346
508
        # pull in the remote revisions so we can diff
347
509
        branch.fetch(other_branch, revision_b)
348
510
        try:
349
511
            revno = branch.revision_id_to_revno(revision_b)
350
 
        except NoSuchRevision:
 
512
        except errors.NoSuchRevision:
351
513
            revno = None
352
514
        return RevisionInfo(branch, revno, revision_b)
353
515