~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: 2007-03-11 21:12:06 UTC
  • mfrom: (2321.2.6 mergeable)
  • Revision ID: pqm@pqm.ubuntu.com-20070311211206-0fd0176ac1e77ef7
(bialix) 0.15 NEWS cleanup

Show diffs side-by-side

added added

removed removed

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