~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: John Arbash Meinel
  • Date: 2006-08-14 16:16:53 UTC
  • mto: (1946.2.6 reduce-knit-churn)
  • mto: This revision was merged to the branch mainline in revision 1919.
  • Revision ID: john@arbash-meinel.com-20060814161653-54cdcdadcd4e9003
Remove bogus entry from BRANCH.TODO

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
import bisect
19
18
import datetime
20
19
import re
21
 
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    revision,
25
 
    symbol_versioning,
26
 
    trace,
27
 
    tsort,
28
 
    )
29
 
 
 
20
import bisect
 
21
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
30
22
 
31
23
_marker = []
32
24
 
33
 
 
34
25
class RevisionInfo(object):
35
26
    """The results of applying a revision specification to a branch.
36
27
 
91
82
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
92
83
            self.revno, self.rev_id, self.branch)
93
84
 
94
 
 
95
85
# classes in this list should have a "prefix" attribute, against which
96
86
# string specs are matched
97
87
SPEC_TYPES = []
98
 
_revno_regex = None
99
 
 
100
88
 
101
89
class RevisionSpec(object):
102
90
    """A parsed revision specification.
117
105
 
118
106
    prefix = None
119
107
 
120
 
    def __new__(cls, spec, _internal=False):
121
 
        if _internal:
122
 
            return object.__new__(cls, spec, _internal=_internal)
123
 
 
124
 
        symbol_versioning.warn('Creating a RevisionSpec directly has'
125
 
                               ' been deprecated in version 0.11. Use'
126
 
                               ' RevisionSpec.from_string()'
127
 
                               ' instead.',
128
 
                               DeprecationWarning, stacklevel=2)
129
 
        return RevisionSpec.from_string(spec)
130
 
 
131
 
    @staticmethod
132
 
    def from_string(spec):
133
 
        """Parse a revision spec string into a RevisionSpec object.
134
 
 
135
 
        :param spec: A string specified by the user
136
 
        :return: A RevisionSpec object that understands how to parse the
137
 
            supplied notation.
 
108
    def __new__(cls, spec, foo=_marker):
 
109
        """Parse a revision specifier.
138
110
        """
139
 
        if not isinstance(spec, (type(None), basestring)):
140
 
            raise TypeError('error')
141
 
 
142
111
        if spec is None:
143
 
            return RevisionSpec(None, _internal=True)
144
 
 
145
 
        assert isinstance(spec, basestring), \
146
 
            "You should only supply strings not %s" % (type(spec),)
147
 
 
148
 
        for spectype in SPEC_TYPES:
149
 
            if spec.startswith(spectype.prefix):
150
 
                trace.mutter('Returning RevisionSpec %s for %s',
151
 
                             spectype.__name__, spec)
152
 
                return spectype(spec, _internal=True)
 
112
            return object.__new__(RevisionSpec, spec)
 
113
 
 
114
        try:
 
115
            spec = int(spec)
 
116
        except ValueError:
 
117
            pass
 
118
 
 
119
        if isinstance(spec, int):
 
120
            return object.__new__(RevisionSpec_int, spec)
 
121
        elif isinstance(spec, basestring):
 
122
            for spectype in SPEC_TYPES:
 
123
                if spec.startswith(spectype.prefix):
 
124
                    return object.__new__(spectype, spec)
 
125
            else:
 
126
                raise BzrError('No namespace registered for string: %r' %
 
127
                               spec)
153
128
        else:
154
 
            # RevisionSpec_revno is special cased, because it is the only
155
 
            # one that directly handles plain integers
156
 
            # TODO: This should not be special cased rather it should be
157
 
            # a method invocation on spectype.canparse()
158
 
            global _revno_regex
159
 
            if _revno_regex is None:
160
 
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
161
 
            if _revno_regex.match(spec) is not None:
162
 
                return RevisionSpec_revno(spec, _internal=True)
163
 
 
164
 
            raise errors.NoSuchRevisionSpec(spec)
165
 
 
166
 
    def __init__(self, spec, _internal=False):
167
 
        """Create a RevisionSpec referring to the Null revision.
168
 
 
169
 
        :param spec: The original spec supplied by the user
170
 
        :param _internal: Used to ensure that RevisionSpec is not being
171
 
            called directly. Only from RevisionSpec.from_string()
172
 
        """
173
 
        if not _internal:
174
 
            # XXX: Update this after 0.10 is released
175
 
            symbol_versioning.warn('Creating a RevisionSpec directly has'
176
 
                                   ' been deprecated in version 0.11. Use'
177
 
                                   ' RevisionSpec.from_string()'
178
 
                                   ' instead.',
179
 
                                   DeprecationWarning, stacklevel=2)
180
 
        self.user_spec = spec
 
129
            raise TypeError('Unhandled revision type %s' % spec)
 
130
 
 
131
    def __init__(self, spec):
181
132
        if self.prefix and spec.startswith(self.prefix):
182
133
            spec = spec[len(self.prefix):]
183
134
        self.spec = spec
184
135
 
185
136
    def _match_on(self, branch, revs):
186
 
        trace.mutter('Returning RevisionSpec._match_on: None')
187
137
        return RevisionInfo(branch, 0, None)
188
138
 
189
139
    def _match_on_and_check(self, branch, revs):
194
144
            # special case - the empty tree
195
145
            return info
196
146
        elif self.prefix:
197
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
147
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
198
148
        else:
199
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
 
149
            raise NoSuchRevision(branch, str(self.spec))
200
150
 
201
151
    def in_history(self, branch):
202
152
        if branch:
203
153
            revs = branch.revision_history()
204
154
        else:
205
 
            # this should never trigger.
206
 
            # TODO: make it a deprecated code path. RBC 20060928
207
155
            revs = None
208
156
        return self._match_on_and_check(branch, revs)
209
157
 
219
167
        
220
168
    def __repr__(self):
221
169
        # this is mostly for helping with testing
222
 
        return '<%s %s>' % (self.__class__.__name__,
223
 
                              self.user_spec)
 
170
        return '<%s %s%s>' % (self.__class__.__name__,
 
171
                              self.prefix or '',
 
172
                              self.spec)
224
173
    
225
174
    def needs_branch(self):
226
175
        """Whether this revision spec needs a branch.
229
178
        """
230
179
        return True
231
180
 
232
 
    def get_branch(self):
233
 
        """When the revision specifier contains a branch location, return it.
234
 
        
235
 
        Otherwise, return None.
236
 
        """
237
 
        return None
238
 
 
239
 
 
240
181
# private API
241
182
 
 
183
class RevisionSpec_int(RevisionSpec):
 
184
    """Spec is a number.  Special case."""
 
185
    def __init__(self, spec):
 
186
        self.spec = int(spec)
 
187
 
 
188
    def _match_on(self, branch, revs):
 
189
        if self.spec < 0:
 
190
            revno = len(revs) + self.spec + 1
 
191
        else:
 
192
            revno = self.spec
 
193
        rev_id = branch.get_rev_id(revno, revs)
 
194
        return RevisionInfo(branch, revno, rev_id)
 
195
 
 
196
 
242
197
class RevisionSpec_revno(RevisionSpec):
243
198
    prefix = 'revno:'
244
199
 
245
200
    def _match_on(self, branch, revs):
246
201
        """Lookup a revision by revision number"""
247
 
        loc = self.spec.find(':')
248
 
        if loc == -1:
249
 
            revno_spec = self.spec
250
 
            branch_spec = None
251
 
        else:
252
 
            revno_spec = self.spec[:loc]
253
 
            branch_spec = self.spec[loc+1:]
254
 
 
255
 
        if revno_spec == '':
256
 
            if not branch_spec:
257
 
                raise errors.InvalidRevisionSpec(self.user_spec,
258
 
                        branch, 'cannot have an empty revno and no branch')
259
 
            revno = None
260
 
        else:
261
 
            try:
262
 
                revno = int(revno_spec)
263
 
                dotted = False
264
 
            except ValueError:
265
 
                # dotted decimal. This arguably should not be here
266
 
                # but the from_string method is a little primitive 
267
 
                # right now - RBC 20060928
268
 
                try:
269
 
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
270
 
                except ValueError, e:
271
 
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
272
 
 
273
 
                dotted = True
274
 
 
275
 
        if branch_spec:
276
 
            # the user has override the branch to look in.
277
 
            # we need to refresh the revision_history map and
278
 
            # the branch object.
279
 
            from bzrlib.branch import Branch
280
 
            branch = Branch.open(branch_spec)
281
 
            # Need to use a new revision history
282
 
            # because we are using a specific branch
283
 
            revs = branch.revision_history()
284
 
 
285
 
        if dotted:
286
 
            branch.lock_read()
287
 
            try:
288
 
                last_rev = branch.last_revision()
289
 
                merge_sorted_revisions = tsort.merge_sort(
290
 
                    branch.repository.get_revision_graph(last_rev),
291
 
                    last_rev,
292
 
                    generate_revno=True)
293
 
                def match(item):
294
 
                    return item[3] == match_revno
295
 
                revisions = filter(match, merge_sorted_revisions)
296
 
            finally:
297
 
                branch.unlock()
298
 
            if len(revisions) != 1:
299
 
                return RevisionInfo(branch, None, None)
300
 
            else:
301
 
                # there is no traditional 'revno' for dotted-decimal revnos.
302
 
                # so for  API compatability we return None.
303
 
                return RevisionInfo(branch, None, revisions[0][1])
304
 
        else:
305
 
            if revno < 0:
306
 
                if (-revno) >= len(revs):
307
 
                    revno = 1
308
 
                else:
309
 
                    revno = len(revs) + revno + 1
310
 
            try:
311
 
                revision_id = branch.get_rev_id(revno, revs)
312
 
            except errors.NoSuchRevision:
313
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
314
 
        return RevisionInfo(branch, revno, revision_id)
 
202
        if self.spec.find(':') == -1:
 
203
            try:
 
204
                return RevisionInfo(branch, int(self.spec))
 
205
            except ValueError:
 
206
                return RevisionInfo(branch, None)
 
207
        else:
 
208
            from branch import Branch
 
209
            revname = self.spec[self.spec.find(':')+1:]
 
210
            other_branch = Branch.open_containing(revname)[0]
 
211
            try:
 
212
                revno = int(self.spec[:self.spec.find(':')])
 
213
            except ValueError:
 
214
                return RevisionInfo(other_branch, None)
 
215
            revid = other_branch.get_rev_id(revno)
 
216
            return RevisionInfo(other_branch, revno)
315
217
        
316
218
    def needs_branch(self):
317
219
        return self.spec.find(':') == -1
318
220
 
319
 
    def get_branch(self):
320
 
        if self.spec.find(':') == -1:
321
 
            return None
322
 
        else:
323
 
            return self.spec[self.spec.find(':')+1:]
324
 
 
325
 
# Old compatibility 
326
 
RevisionSpec_int = RevisionSpec_revno
327
 
 
328
221
SPEC_TYPES.append(RevisionSpec_revno)
329
222
 
330
223
 
333
226
 
334
227
    def _match_on(self, branch, revs):
335
228
        try:
336
 
            revno = revs.index(self.spec) + 1
 
229
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
337
230
        except ValueError:
338
 
            revno = None
339
 
        return RevisionInfo(branch, revno, self.spec)
 
231
            return RevisionInfo(branch, None, self.spec)
340
232
 
341
233
SPEC_TYPES.append(RevisionSpec_revid)
342
234
 
346
238
    prefix = 'last:'
347
239
 
348
240
    def _match_on(self, branch, revs):
349
 
        if self.spec == '':
350
 
            if not revs:
351
 
                raise errors.NoCommits(branch)
352
 
            return RevisionInfo(branch, len(revs), revs[-1])
353
 
 
354
241
        try:
355
242
            offset = int(self.spec)
356
 
        except ValueError, e:
357
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
358
 
 
359
 
        if offset <= 0:
360
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
361
 
                                             'you must supply a positive value')
362
 
        revno = len(revs) - offset + 1
363
 
        try:
364
 
            revision_id = branch.get_rev_id(revno, revs)
365
 
        except errors.NoSuchRevision:
366
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
367
 
        return RevisionInfo(branch, revno, revision_id)
 
243
        except ValueError:
 
244
            return RevisionInfo(branch, None)
 
245
        else:
 
246
            if offset <= 0:
 
247
                raise BzrError('You must supply a positive value for --revision last:XXX')
 
248
            return RevisionInfo(branch, len(revs) - offset + 1)
368
249
 
369
250
SPEC_TYPES.append(RevisionSpec_last)
370
251
 
374
255
    prefix = 'before:'
375
256
    
376
257
    def _match_on(self, branch, revs):
377
 
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
378
 
        if r.revno == 0:
379
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
380
 
                                         'cannot go before the null: revision')
381
 
        if r.revno is None:
382
 
            # We need to use the repository history here
383
 
            rev = branch.repository.get_revision(r.rev_id)
384
 
            if not rev.parent_ids:
385
 
                revno = 0
386
 
                revision_id = None
387
 
            else:
388
 
                revision_id = rev.parent_ids[0]
389
 
                try:
390
 
                    revno = revs.index(revision_id) + 1
391
 
                except ValueError:
392
 
                    revno = None
393
 
        else:
394
 
            revno = r.revno - 1
395
 
            try:
396
 
                revision_id = branch.get_rev_id(revno, revs)
397
 
            except errors.NoSuchRevision:
398
 
                raise errors.InvalidRevisionSpec(self.user_spec,
399
 
                                                 branch)
400
 
        return RevisionInfo(branch, revno, revision_id)
 
258
        r = RevisionSpec(self.spec)._match_on(branch, revs)
 
259
        if (r.revno is None) or (r.revno == 0):
 
260
            return r
 
261
        return RevisionInfo(branch, r.revno - 1)
401
262
 
402
263
SPEC_TYPES.append(RevisionSpec_before)
403
264
 
406
267
    prefix = 'tag:'
407
268
 
408
269
    def _match_on(self, branch, revs):
409
 
        raise errors.InvalidRevisionSpec(self.user_spec, branch,
410
 
                                         'tag: namespace registered,'
411
 
                                         ' but not implemented')
 
270
        raise BzrError('tag: namespace registered, but not implemented.')
412
271
 
413
272
SPEC_TYPES.append(RevisionSpec_tag)
414
273
 
415
274
 
416
 
class _RevListToTimestamps(object):
417
 
    """This takes a list of revisions, and allows you to bisect by date"""
418
 
 
419
 
    __slots__ = ['revs', 'branch']
420
 
 
 
275
class RevisionSpec_revs:
421
276
    def __init__(self, revs, branch):
422
277
        self.revs = revs
423
278
        self.branch = branch
424
 
 
425
279
    def __getitem__(self, index):
426
 
        """Get the date of the index'd item"""
427
280
        r = self.branch.repository.get_revision(self.revs[index])
428
281
        # TODO: Handle timezone.
429
282
        return datetime.datetime.fromtimestamp(r.timestamp)
430
 
 
431
283
    def __len__(self):
432
284
        return len(self.revs)
433
285
 
461
313
        else:
462
314
            m = self._date_re.match(self.spec)
463
315
            if not m or (not m.group('date') and not m.group('time')):
464
 
                raise errors.InvalidRevisionSpec(self.user_spec,
465
 
                                                 branch, 'invalid date')
466
 
 
467
 
            try:
468
 
                if m.group('date'):
469
 
                    year = int(m.group('year'))
470
 
                    month = int(m.group('month'))
471
 
                    day = int(m.group('day'))
472
 
                else:
473
 
                    year = today.year
474
 
                    month = today.month
475
 
                    day = today.day
476
 
 
477
 
                if m.group('time'):
478
 
                    hour = int(m.group('hour'))
479
 
                    minute = int(m.group('minute'))
480
 
                    if m.group('second'):
481
 
                        second = int(m.group('second'))
482
 
                    else:
483
 
                        second = 0
484
 
                else:
485
 
                    hour, minute, second = 0,0,0
486
 
            except ValueError:
487
 
                raise errors.InvalidRevisionSpec(self.user_spec,
488
 
                                                 branch, 'invalid date')
 
316
                raise BzrError('Invalid revision date %r' % self.spec)
 
317
 
 
318
            if m.group('date'):
 
319
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
 
320
            else:
 
321
                year, month, day = today.year, today.month, today.day
 
322
            if m.group('time'):
 
323
                hour = int(m.group('hour'))
 
324
                minute = int(m.group('minute'))
 
325
                if m.group('second'):
 
326
                    second = int(m.group('second'))
 
327
                else:
 
328
                    second = 0
 
329
            else:
 
330
                hour, minute, second = 0,0,0
489
331
 
490
332
            dt = datetime.datetime(year=year, month=month, day=day,
491
333
                    hour=hour, minute=minute, second=second)
492
334
        branch.lock_read()
493
335
        try:
494
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
336
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
495
337
        finally:
496
338
            branch.unlock()
497
339
        if rev == len(revs):
506
348
    prefix = 'ancestor:'
507
349
 
508
350
    def _match_on(self, branch, revs):
509
 
        from bzrlib.branch import Branch
510
 
 
511
 
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
512
 
        other_branch = Branch.open(self.spec)
 
351
        from branch import Branch
 
352
        from revision import common_ancestor, MultipleRevisionSources
 
353
        other_branch = Branch.open_containing(self.spec)[0]
513
354
        revision_a = branch.last_revision()
514
355
        revision_b = other_branch.last_revision()
515
356
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
516
 
            if r in (None, revision.NULL_REVISION):
517
 
                raise errors.NoCommits(b)
518
 
        revision_source = revision.MultipleRevisionSources(
519
 
                branch.repository, other_branch.repository)
520
 
        rev_id = revision.common_ancestor(revision_a, revision_b,
521
 
                                          revision_source)
 
357
            if r is None:
 
358
                raise NoCommits(b)
 
359
        revision_source = MultipleRevisionSources(branch.repository,
 
360
                                                  other_branch.repository)
 
361
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
522
362
        try:
523
363
            revno = branch.revision_id_to_revno(rev_id)
524
 
        except errors.NoSuchRevision:
 
364
        except NoSuchRevision:
525
365
            revno = None
526
366
        return RevisionInfo(branch, revno, rev_id)
527
367
        
528
368
SPEC_TYPES.append(RevisionSpec_ancestor)
529
369
 
530
 
 
531
370
class RevisionSpec_branch(RevisionSpec):
532
371
    """A branch: revision specifier.
533
372
 
536
375
    prefix = 'branch:'
537
376
 
538
377
    def _match_on(self, branch, revs):
539
 
        from bzrlib.branch import Branch
540
 
        other_branch = Branch.open(self.spec)
 
378
        from branch import Branch
 
379
        other_branch = Branch.open_containing(self.spec)[0]
541
380
        revision_b = other_branch.last_revision()
542
 
        if revision_b in (None, revision.NULL_REVISION):
543
 
            raise errors.NoCommits(other_branch)
 
381
        if revision_b is None:
 
382
            raise NoCommits(other_branch)
544
383
        # pull in the remote revisions so we can diff
545
384
        branch.fetch(other_branch, revision_b)
546
385
        try:
547
386
            revno = branch.revision_id_to_revno(revision_b)
548
 
        except errors.NoSuchRevision:
 
387
        except NoSuchRevision:
549
388
            revno = None
550
389
        return RevisionInfo(branch, revno, revision_b)
551
390