~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

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