~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-08-17 07:52:09 UTC
  • mfrom: (1910.3.4 trivial)
  • Revision ID: pqm@pqm.ubuntu.com-20060817075209-e85a1f9e05ff8b87
(andrew) Trivial fixes to NotImplemented errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
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
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
 
    osutils,
25
 
    revision,
26
 
    symbol_versioning,
27
 
    trace,
28
 
    tsort,
29
 
    )
30
 
 
 
20
import bisect
 
21
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
31
22
 
32
23
_marker = []
33
24
 
34
 
 
35
25
class RevisionInfo(object):
36
 
    """The results of applying a revision specification to a branch."""
37
 
 
38
 
    help_txt = """The results of applying a revision specification to a branch.
 
26
    """The results of applying a revision specification to a branch.
39
27
 
40
28
    An instance has two useful attributes: revno, and rev_id.
41
29
 
94
82
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
95
83
            self.revno, self.rev_id, self.branch)
96
84
 
97
 
    @staticmethod
98
 
    def from_revision_id(branch, revision_id, revs):
99
 
        """Construct a RevisionInfo given just the id.
100
 
 
101
 
        Use this if you don't know or care what the revno is.
102
 
        """
103
 
        try:
104
 
            revno = revs.index(revision_id) + 1
105
 
        except ValueError:
106
 
            revno = None
107
 
        return RevisionInfo(branch, revno, revision_id)
108
 
 
109
 
 
110
85
# classes in this list should have a "prefix" attribute, against which
111
86
# string specs are matched
112
87
SPEC_TYPES = []
113
 
_revno_regex = None
114
 
 
115
88
 
116
89
class RevisionSpec(object):
117
 
    """A parsed revision specification."""
118
 
 
119
 
    help_txt = """A parsed revision specification.
 
90
    """A parsed revision specification.
120
91
 
121
92
    A revision specification can be an integer, in which case it is
122
93
    assumed to be a revno (though this will translate negative values
134
105
 
135
106
    prefix = None
136
107
 
137
 
    def __new__(cls, spec, _internal=False):
138
 
        if _internal:
139
 
            return object.__new__(cls, spec, _internal=_internal)
140
 
 
141
 
        symbol_versioning.warn('Creating a RevisionSpec directly has'
142
 
                               ' been deprecated in version 0.11. Use'
143
 
                               ' RevisionSpec.from_string()'
144
 
                               ' instead.',
145
 
                               DeprecationWarning, stacklevel=2)
146
 
        return RevisionSpec.from_string(spec)
147
 
 
148
 
    @staticmethod
149
 
    def from_string(spec):
150
 
        """Parse a revision spec string into a RevisionSpec object.
151
 
 
152
 
        :param spec: A string specified by the user
153
 
        :return: A RevisionSpec object that understands how to parse the
154
 
            supplied notation.
 
108
    def __new__(cls, spec, foo=_marker):
 
109
        """Parse a revision specifier.
155
110
        """
156
 
        if not isinstance(spec, (type(None), basestring)):
157
 
            raise TypeError('error')
158
 
 
159
111
        if spec is None:
160
 
            return RevisionSpec(None, _internal=True)
161
 
 
162
 
        assert isinstance(spec, basestring), \
163
 
            "You should only supply strings not %s" % (type(spec),)
164
 
 
165
 
        for spectype in SPEC_TYPES:
166
 
            if spec.startswith(spectype.prefix):
167
 
                trace.mutter('Returning RevisionSpec %s for %s',
168
 
                             spectype.__name__, spec)
169
 
                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)
170
128
        else:
171
 
            # RevisionSpec_revno is special cased, because it is the only
172
 
            # one that directly handles plain integers
173
 
            # TODO: This should not be special cased rather it should be
174
 
            # a method invocation on spectype.canparse()
175
 
            global _revno_regex
176
 
            if _revno_regex is None:
177
 
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
178
 
            if _revno_regex.match(spec) is not None:
179
 
                return RevisionSpec_revno(spec, _internal=True)
180
 
 
181
 
            raise errors.NoSuchRevisionSpec(spec)
182
 
 
183
 
    def __init__(self, spec, _internal=False):
184
 
        """Create a RevisionSpec referring to the Null revision.
185
 
 
186
 
        :param spec: The original spec supplied by the user
187
 
        :param _internal: Used to ensure that RevisionSpec is not being
188
 
            called directly. Only from RevisionSpec.from_string()
189
 
        """
190
 
        if not _internal:
191
 
            # XXX: Update this after 0.10 is released
192
 
            symbol_versioning.warn('Creating a RevisionSpec directly has'
193
 
                                   ' been deprecated in version 0.11. Use'
194
 
                                   ' RevisionSpec.from_string()'
195
 
                                   ' instead.',
196
 
                                   DeprecationWarning, stacklevel=2)
197
 
        self.user_spec = spec
 
129
            raise TypeError('Unhandled revision type %s' % spec)
 
130
 
 
131
    def __init__(self, spec):
198
132
        if self.prefix and spec.startswith(self.prefix):
199
133
            spec = spec[len(self.prefix):]
200
134
        self.spec = spec
201
135
 
202
136
    def _match_on(self, branch, revs):
203
 
        trace.mutter('Returning RevisionSpec._match_on: None')
204
137
        return RevisionInfo(branch, 0, None)
205
138
 
206
139
    def _match_on_and_check(self, branch, revs):
211
144
            # special case - the empty tree
212
145
            return info
213
146
        elif self.prefix:
214
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
147
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
215
148
        else:
216
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
 
149
            raise NoSuchRevision(branch, str(self.spec))
217
150
 
218
151
    def in_history(self, branch):
219
152
        if branch:
220
153
            revs = branch.revision_history()
221
154
        else:
222
 
            # this should never trigger.
223
 
            # TODO: make it a deprecated code path. RBC 20060928
224
155
            revs = None
225
156
        return self._match_on_and_check(branch, revs)
226
157
 
236
167
        
237
168
    def __repr__(self):
238
169
        # this is mostly for helping with testing
239
 
        return '<%s %s>' % (self.__class__.__name__,
240
 
                              self.user_spec)
 
170
        return '<%s %s%s>' % (self.__class__.__name__,
 
171
                              self.prefix or '',
 
172
                              self.spec)
241
173
    
242
174
    def needs_branch(self):
243
175
        """Whether this revision spec needs a branch.
246
178
        """
247
179
        return True
248
180
 
249
 
    def get_branch(self):
250
 
        """When the revision specifier contains a branch location, return it.
251
 
        
252
 
        Otherwise, return None.
253
 
        """
254
 
        return None
255
 
 
256
 
 
257
181
# private API
258
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
 
259
197
class RevisionSpec_revno(RevisionSpec):
260
 
    """Selects a revision using a number."""
261
 
 
262
 
    help_txt = """Selects a revision using a number.
263
 
 
264
 
    Use an integer to specify a revision in the history of the branch.
265
 
    Optionally a branch can be specified. The 'revno:' prefix is optional.
266
 
    A negative number will count from the end of the branch (-1 is the
267
 
    last revision, -2 the previous one). If the negative number is larger
268
 
    than the branch's history, the first revision is returned.
269
 
    Examples::
270
 
 
271
 
      revno:1                   -> return the first revision
272
 
      revno:3:/path/to/branch   -> return the 3rd revision of
273
 
                                   the branch '/path/to/branch'
274
 
      revno:-1                  -> The last revision in a branch.
275
 
      -2:http://other/branch    -> The second to last revision in the
276
 
                                   remote branch.
277
 
      -1000000                  -> Most likely the first revision, unless
278
 
                                   your history is very long.
279
 
    """
280
198
    prefix = 'revno:'
281
199
 
282
200
    def _match_on(self, branch, revs):
283
201
        """Lookup a revision by revision number"""
284
 
        loc = self.spec.find(':')
285
 
        if loc == -1:
286
 
            revno_spec = self.spec
287
 
            branch_spec = None
288
 
        else:
289
 
            revno_spec = self.spec[:loc]
290
 
            branch_spec = self.spec[loc+1:]
291
 
 
292
 
        if revno_spec == '':
293
 
            if not branch_spec:
294
 
                raise errors.InvalidRevisionSpec(self.user_spec,
295
 
                        branch, 'cannot have an empty revno and no branch')
296
 
            revno = None
297
 
        else:
298
 
            try:
299
 
                revno = int(revno_spec)
300
 
                dotted = False
301
 
            except ValueError:
302
 
                # dotted decimal. This arguably should not be here
303
 
                # but the from_string method is a little primitive 
304
 
                # right now - RBC 20060928
305
 
                try:
306
 
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
307
 
                except ValueError, e:
308
 
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
309
 
 
310
 
                dotted = True
311
 
 
312
 
        if branch_spec:
313
 
            # the user has override the branch to look in.
314
 
            # we need to refresh the revision_history map and
315
 
            # the branch object.
316
 
            from bzrlib.branch import Branch
317
 
            branch = Branch.open(branch_spec)
318
 
            # Need to use a new revision history
319
 
            # because we are using a specific branch
320
 
            revs = branch.revision_history()
321
 
 
322
 
        if dotted:
323
 
            branch.lock_read()
324
 
            try:
325
 
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
326
 
                revisions = [revision_id for revision_id, revno
327
 
                             in revision_id_to_revno.iteritems()
328
 
                             if revno == match_revno]
329
 
            finally:
330
 
                branch.unlock()
331
 
            if len(revisions) != 1:
332
 
                return RevisionInfo(branch, None, None)
333
 
            else:
334
 
                # there is no traditional 'revno' for dotted-decimal revnos.
335
 
                # so for  API compatability we return None.
336
 
                return RevisionInfo(branch, None, revisions[0])
337
 
        else:
338
 
            if revno < 0:
339
 
                # if get_rev_id supported negative revnos, there would not be a
340
 
                # need for this special case.
341
 
                if (-revno) >= len(revs):
342
 
                    revno = 1
343
 
                else:
344
 
                    revno = len(revs) + revno + 1
345
 
            try:
346
 
                revision_id = branch.get_rev_id(revno, revs)
347
 
            except errors.NoSuchRevision:
348
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
349
 
        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)
350
217
        
351
218
    def needs_branch(self):
352
219
        return self.spec.find(':') == -1
353
220
 
354
 
    def get_branch(self):
355
 
        if self.spec.find(':') == -1:
356
 
            return None
357
 
        else:
358
 
            return self.spec[self.spec.find(':')+1:]
359
 
 
360
 
# Old compatibility 
361
 
RevisionSpec_int = RevisionSpec_revno
362
 
 
363
221
SPEC_TYPES.append(RevisionSpec_revno)
364
222
 
365
223
 
366
224
class RevisionSpec_revid(RevisionSpec):
367
 
    """Selects a revision using the revision id."""
368
 
 
369
 
    help_txt = """Selects a revision using the revision id.
370
 
 
371
 
    Supply a specific revision id, that can be used to specify any
372
 
    revision id in the ancestry of the branch. 
373
 
    Including merges, and pending merges.
374
 
    Examples::
375
 
 
376
 
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
377
 
    """    
378
225
    prefix = 'revid:'
379
226
 
380
227
    def _match_on(self, branch, revs):
381
 
        # self.spec comes straight from parsing the command line arguments,
382
 
        # so we expect it to be a Unicode string. Switch it to the internal
383
 
        # representation.
384
 
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
385
 
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
228
        try:
 
229
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
 
230
        except ValueError:
 
231
            return RevisionInfo(branch, None, self.spec)
386
232
 
387
233
SPEC_TYPES.append(RevisionSpec_revid)
388
234
 
389
235
 
390
236
class RevisionSpec_last(RevisionSpec):
391
 
    """Selects the nth revision from the end."""
392
 
 
393
 
    help_txt = """Selects the nth revision from the end.
394
 
 
395
 
    Supply a positive number to get the nth revision from the end.
396
 
    This is the same as supplying negative numbers to the 'revno:' spec.
397
 
    Examples::
398
 
 
399
 
      last:1        -> return the last revision
400
 
      last:3        -> return the revision 2 before the end.
401
 
    """    
402
237
 
403
238
    prefix = 'last:'
404
239
 
405
240
    def _match_on(self, branch, revs):
406
 
        if self.spec == '':
407
 
            if not revs:
408
 
                raise errors.NoCommits(branch)
409
 
            return RevisionInfo(branch, len(revs), revs[-1])
410
 
 
411
241
        try:
412
242
            offset = int(self.spec)
413
 
        except ValueError, e:
414
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
415
 
 
416
 
        if offset <= 0:
417
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
418
 
                                             'you must supply a positive value')
419
 
        revno = len(revs) - offset + 1
420
 
        try:
421
 
            revision_id = branch.get_rev_id(revno, revs)
422
 
        except errors.NoSuchRevision:
423
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
424
 
        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)
425
249
 
426
250
SPEC_TYPES.append(RevisionSpec_last)
427
251
 
428
252
 
429
253
class RevisionSpec_before(RevisionSpec):
430
 
    """Selects the parent of the revision specified."""
431
 
 
432
 
    help_txt = """Selects the parent of the revision specified.
433
 
 
434
 
    Supply any revision spec to return the parent of that revision.
435
 
    It is an error to request the parent of the null revision (before:0).
436
 
    This is mostly useful when inspecting revisions that are not in the
437
 
    revision history of a branch.
438
 
 
439
 
    Examples::
440
 
 
441
 
      before:1913    -> Return the parent of revno 1913 (revno 1912)
442
 
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
443
 
                                            aaaa@bbbb-1234567890
444
 
      bzr diff -r before:revid:aaaa..revid:aaaa
445
 
            -> Find the changes between revision 'aaaa' and its parent.
446
 
               (what changes did 'aaaa' introduce)
447
 
    """
448
254
 
449
255
    prefix = 'before:'
450
256
    
451
257
    def _match_on(self, branch, revs):
452
 
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
453
 
        if r.revno == 0:
454
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
455
 
                                         'cannot go before the null: revision')
456
 
        if r.revno is None:
457
 
            # We need to use the repository history here
458
 
            rev = branch.repository.get_revision(r.rev_id)
459
 
            if not rev.parent_ids:
460
 
                revno = 0
461
 
                revision_id = revision.NULL_REVISION
462
 
            else:
463
 
                revision_id = rev.parent_ids[0]
464
 
                try:
465
 
                    revno = revs.index(revision_id) + 1
466
 
                except ValueError:
467
 
                    revno = None
468
 
        else:
469
 
            revno = r.revno - 1
470
 
            try:
471
 
                revision_id = branch.get_rev_id(revno, revs)
472
 
            except errors.NoSuchRevision:
473
 
                raise errors.InvalidRevisionSpec(self.user_spec,
474
 
                                                 branch)
475
 
        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)
476
262
 
477
263
SPEC_TYPES.append(RevisionSpec_before)
478
264
 
479
265
 
480
266
class RevisionSpec_tag(RevisionSpec):
481
 
    """Select a revision identified by tag name"""
482
 
 
483
 
    help_txt = """Selects a revision identified by a tag name.
484
 
 
485
 
    Tags are stored in the branch and created by the 'tag' command.
486
 
    """
487
 
 
488
267
    prefix = 'tag:'
489
268
 
490
269
    def _match_on(self, branch, revs):
491
 
        # Can raise tags not supported, NoSuchTag, etc
492
 
        return RevisionInfo.from_revision_id(branch,
493
 
            branch.tags.lookup_tag(self.spec),
494
 
            revs)
 
270
        raise BzrError('tag: namespace registered, but not implemented.')
495
271
 
496
272
SPEC_TYPES.append(RevisionSpec_tag)
497
273
 
498
274
 
499
 
class _RevListToTimestamps(object):
500
 
    """This takes a list of revisions, and allows you to bisect by date"""
501
 
 
502
 
    __slots__ = ['revs', 'branch']
503
 
 
 
275
class RevisionSpec_revs:
504
276
    def __init__(self, revs, branch):
505
277
        self.revs = revs
506
278
        self.branch = branch
507
 
 
508
279
    def __getitem__(self, index):
509
 
        """Get the date of the index'd item"""
510
280
        r = self.branch.repository.get_revision(self.revs[index])
511
281
        # TODO: Handle timezone.
512
282
        return datetime.datetime.fromtimestamp(r.timestamp)
513
 
 
514
283
    def __len__(self):
515
284
        return len(self.revs)
516
285
 
517
286
 
518
287
class RevisionSpec_date(RevisionSpec):
519
 
    """Selects a revision on the basis of a datestamp."""
520
 
 
521
 
    help_txt = """Selects a revision on the basis of a datestamp.
522
 
 
523
 
    Supply a datestamp to select the first revision that matches the date.
524
 
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
525
 
    Matches the first entry after a given date (either at midnight or
526
 
    at a specified time).
527
 
 
528
 
    One way to display all the changes since yesterday would be::
529
 
 
530
 
        bzr log -r date:yesterday..-1
531
 
 
532
 
    Examples::
533
 
 
534
 
      date:yesterday            -> select the first revision since yesterday
535
 
      date:2006-08-14,17:10:14  -> select the first revision after
536
 
                                   August 14th, 2006 at 5:10pm.
537
 
    """    
538
288
    prefix = 'date:'
539
289
    _date_re = re.compile(
540
290
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
543
293
        )
544
294
 
545
295
    def _match_on(self, branch, revs):
546
 
        """Spec for date revisions:
 
296
        """
 
297
        Spec for date revisions:
547
298
          date:value
548
299
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
549
300
          matches the first entry after a given date (either at midnight or
550
301
          at a specified time).
 
302
 
 
303
          So the proper way of saying 'give me all entries for today' is:
 
304
              -r date:yesterday..date:today
551
305
        """
552
 
        #  XXX: This doesn't actually work
553
 
        #  So the proper way of saying 'give me all entries for today' is:
554
 
        #      -r date:yesterday..date:today
555
306
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
556
307
        if self.spec.lower() == 'yesterday':
557
308
            dt = today - datetime.timedelta(days=1)
562
313
        else:
563
314
            m = self._date_re.match(self.spec)
564
315
            if not m or (not m.group('date') and not m.group('time')):
565
 
                raise errors.InvalidRevisionSpec(self.user_spec,
566
 
                                                 branch, 'invalid date')
567
 
 
568
 
            try:
569
 
                if m.group('date'):
570
 
                    year = int(m.group('year'))
571
 
                    month = int(m.group('month'))
572
 
                    day = int(m.group('day'))
573
 
                else:
574
 
                    year = today.year
575
 
                    month = today.month
576
 
                    day = today.day
577
 
 
578
 
                if m.group('time'):
579
 
                    hour = int(m.group('hour'))
580
 
                    minute = int(m.group('minute'))
581
 
                    if m.group('second'):
582
 
                        second = int(m.group('second'))
583
 
                    else:
584
 
                        second = 0
585
 
                else:
586
 
                    hour, minute, second = 0,0,0
587
 
            except ValueError:
588
 
                raise errors.InvalidRevisionSpec(self.user_spec,
589
 
                                                 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
590
331
 
591
332
            dt = datetime.datetime(year=year, month=month, day=day,
592
333
                    hour=hour, minute=minute, second=second)
593
334
        branch.lock_read()
594
335
        try:
595
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
336
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
596
337
        finally:
597
338
            branch.unlock()
598
339
        if rev == len(revs):
604
345
 
605
346
 
606
347
class RevisionSpec_ancestor(RevisionSpec):
607
 
    """Selects a common ancestor with a second branch."""
608
 
 
609
 
    help_txt = """Selects a common ancestor with a second branch.
610
 
 
611
 
    Supply the path to a branch to select the common ancestor.
612
 
 
613
 
    The common ancestor is the last revision that existed in both
614
 
    branches. Usually this is the branch point, but it could also be
615
 
    a revision that was merged.
616
 
 
617
 
    This is frequently used with 'diff' to return all of the changes
618
 
    that your branch introduces, while excluding the changes that you
619
 
    have not merged from the remote branch.
620
 
 
621
 
    Examples::
622
 
 
623
 
      ancestor:/path/to/branch
624
 
      $ bzr diff -r ancestor:../../mainline/branch
625
 
    """
626
348
    prefix = 'ancestor:'
627
349
 
628
350
    def _match_on(self, branch, revs):
629
 
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
630
 
        return self._find_revision_info(branch, self.spec)
631
 
 
632
 
    @staticmethod
633
 
    def _find_revision_info(branch, other_location):
634
 
        from bzrlib.branch import Branch
635
 
 
636
 
        other_branch = Branch.open(other_location)
 
351
        from branch import Branch
 
352
        from revision import common_ancestor, MultipleRevisionSources
 
353
        other_branch = Branch.open_containing(self.spec)[0]
637
354
        revision_a = branch.last_revision()
638
355
        revision_b = other_branch.last_revision()
639
356
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
640
 
            if r in (None, revision.NULL_REVISION):
641
 
                raise errors.NoCommits(b)
642
 
        revision_source = revision.MultipleRevisionSources(
643
 
                branch.repository, other_branch.repository)
644
 
        graph = branch.repository.get_graph(other_branch.repository)
645
 
        revision_a = revision.ensure_null(revision_a)
646
 
        revision_b = revision.ensure_null(revision_b)
647
 
        if revision.NULL_REVISION in (revision_a, revision_b):
648
 
            rev_id = revision.NULL_REVISION
649
 
        else:
650
 
            rev_id = graph.find_unique_lca(revision_a, revision_b)
651
 
            if rev_id == revision.NULL_REVISION:
652
 
                raise errors.NoCommonAncestor(revision_a, revision_b)
 
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)
653
362
        try:
654
363
            revno = branch.revision_id_to_revno(rev_id)
655
 
        except errors.NoSuchRevision:
 
364
        except NoSuchRevision:
656
365
            revno = None
657
366
        return RevisionInfo(branch, revno, rev_id)
658
 
 
659
 
 
 
367
        
660
368
SPEC_TYPES.append(RevisionSpec_ancestor)
661
369
 
662
 
 
663
370
class RevisionSpec_branch(RevisionSpec):
664
 
    """Selects the last revision of a specified branch."""
665
 
 
666
 
    help_txt = """Selects the last revision of a specified branch.
667
 
 
668
 
    Supply the path to a branch to select its last revision.
669
 
 
670
 
    Examples::
671
 
 
672
 
      branch:/path/to/branch
 
371
    """A branch: revision specifier.
 
372
 
 
373
    This takes the path to a branch and returns its tip revision id.
673
374
    """
674
375
    prefix = 'branch:'
675
376
 
676
377
    def _match_on(self, branch, revs):
677
 
        from bzrlib.branch import Branch
678
 
        other_branch = Branch.open(self.spec)
 
378
        from branch import Branch
 
379
        other_branch = Branch.open_containing(self.spec)[0]
679
380
        revision_b = other_branch.last_revision()
680
 
        if revision_b in (None, revision.NULL_REVISION):
681
 
            raise errors.NoCommits(other_branch)
 
381
        if revision_b is None:
 
382
            raise NoCommits(other_branch)
682
383
        # pull in the remote revisions so we can diff
683
384
        branch.fetch(other_branch, revision_b)
684
385
        try:
685
386
            revno = branch.revision_id_to_revno(revision_b)
686
 
        except errors.NoSuchRevision:
 
387
        except NoSuchRevision:
687
388
            revno = None
688
389
        return RevisionInfo(branch, revno, revision_b)
689
390
        
690
391
SPEC_TYPES.append(RevisionSpec_branch)
691
 
 
692
 
 
693
 
class RevisionSpec_submit(RevisionSpec_ancestor):
694
 
    """Selects a common ancestor with a submit branch."""
695
 
 
696
 
    help_txt = """Selects a common ancestor with the submit branch.
697
 
 
698
 
    Diffing against this shows all the changes that were made in this branch,
699
 
    and is a good predictor of what merge will do.  The submit branch is
700
 
    used by the bundle and merge directive comands.  If no submit branch
701
 
    is specified, the parent branch is used instead.
702
 
 
703
 
    The common ancestor is the last revision that existed in both
704
 
    branches. Usually this is the branch point, but it could also be
705
 
    a revision that was merged.
706
 
 
707
 
    Examples::
708
 
 
709
 
      $ bzr diff -r submit:
710
 
    """
711
 
 
712
 
    prefix = 'submit:'
713
 
 
714
 
    def _match_on(self, branch, revs):
715
 
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
716
 
        submit_location = branch.get_submit_branch()
717
 
        location_type = 'submit branch'
718
 
        if submit_location is None:
719
 
            submit_location = branch.get_parent()
720
 
            location_type = 'parent branch'
721
 
        if submit_location is None:
722
 
            raise errors.NoSubmitBranch(branch)
723
 
        trace.note('Using %s %s', location_type, submit_location)
724
 
        return self._find_revision_info(branch, submit_location)
725
 
 
726
 
 
727
 
SPEC_TYPES.append(RevisionSpec_submit)