/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: John Arbash Meinel
  • Date: 2009-09-24 19:26:45 UTC
  • mto: (4634.52.3 2.0)
  • mto: This revision was merged to the branch mainline in revision 4716.
  • Revision ID: john@arbash-meinel.com-20090924192645-hyy1ycnnk6u3j5j6
Catch a corner case that we were missing.
The CHKInventory tests were passing, but failed for test_inv because
we were passing None to _getitems(). That only failed for InternalNodes,
but we were using a structure that didn't have internal nodes.
So now the test is parameterized on a small CHKInventory page size
to force those things out into the open.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 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
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
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
import re
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
18
22
import bisect
19
23
import datetime
20
 
import re
 
24
""")
21
25
 
22
26
from bzrlib import (
23
27
    errors,
 
28
    osutils,
 
29
    registry,
24
30
    revision,
25
31
    symbol_versioning,
26
32
    trace,
31
37
 
32
38
 
33
39
class RevisionInfo(object):
34
 
    """The results of applying a revision specification to a branch.
 
40
    """The results of applying a revision specification to a branch."""
 
41
 
 
42
    help_txt = """The results of applying a revision specification to a branch.
35
43
 
36
44
    An instance has two useful attributes: revno, and rev_id.
37
45
 
90
98
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
91
99
            self.revno, self.rev_id, self.branch)
92
100
 
 
101
    @staticmethod
 
102
    def from_revision_id(branch, revision_id, revs):
 
103
        """Construct a RevisionInfo given just the id.
 
104
 
 
105
        Use this if you don't know or care what the revno is.
 
106
        """
 
107
        if revision_id == revision.NULL_REVISION:
 
108
            return RevisionInfo(branch, 0, revision_id)
 
109
        try:
 
110
            revno = revs.index(revision_id) + 1
 
111
        except ValueError:
 
112
            revno = None
 
113
        return RevisionInfo(branch, revno, revision_id)
 
114
 
93
115
 
94
116
# classes in this list should have a "prefix" attribute, against which
95
117
# string specs are matched
96
 
SPEC_TYPES = []
97
118
_revno_regex = None
98
119
 
99
120
 
100
121
class RevisionSpec(object):
101
 
    """A parsed revision specification.
 
122
    """A parsed revision specification."""
 
123
 
 
124
    help_txt = """A parsed revision specification.
102
125
 
103
126
    A revision specification can be an integer, in which case it is
104
127
    assumed to be a revno (though this will translate negative values
115
138
    """
116
139
 
117
140
    prefix = None
118
 
 
119
 
    def __new__(cls, spec, _internal=False):
120
 
        if _internal:
121
 
            return object.__new__(cls, spec, _internal=_internal)
122
 
 
123
 
        symbol_versioning.warn('Creating a RevisionSpec directly has'
124
 
                               ' been deprecated in version 0.11. Use'
125
 
                               ' RevisionSpec.from_string()'
126
 
                               ' instead.',
127
 
                               DeprecationWarning, stacklevel=2)
128
 
        return RevisionSpec.from_string(spec)
 
141
    wants_revision_history = True
129
142
 
130
143
    @staticmethod
131
144
    def from_string(spec):
140
153
 
141
154
        if spec is None:
142
155
            return RevisionSpec(None, _internal=True)
143
 
 
144
 
        assert isinstance(spec, basestring), \
145
 
            "You should only supply strings not %s" % (type(spec),)
146
 
 
147
 
        for spectype in SPEC_TYPES:
148
 
            if spec.startswith(spectype.prefix):
149
 
                trace.mutter('Returning RevisionSpec %s for %s',
150
 
                             spectype.__name__, spec)
151
 
                return spectype(spec, _internal=True)
 
156
        match = revspec_registry.get_prefix(spec)
 
157
        if match is not None:
 
158
            spectype, specsuffix = match
 
159
            trace.mutter('Returning RevisionSpec %s for %s',
 
160
                         spectype.__name__, spec)
 
161
            return spectype(spec, _internal=True)
152
162
        else:
 
163
            for spectype in SPEC_TYPES:
 
164
                if spec.startswith(spectype.prefix):
 
165
                    trace.mutter('Returning RevisionSpec %s for %s',
 
166
                                 spectype.__name__, spec)
 
167
                    return spectype(spec, _internal=True)
153
168
            # RevisionSpec_revno is special cased, because it is the only
154
169
            # one that directly handles plain integers
 
170
            # TODO: This should not be special cased rather it should be
 
171
            # a method invocation on spectype.canparse()
155
172
            global _revno_regex
156
173
            if _revno_regex is None:
157
 
                _revno_regex = re.compile(r'-?\d+(:.*)?$')
 
174
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
158
175
            if _revno_regex.match(spec) is not None:
159
176
                return RevisionSpec_revno(spec, _internal=True)
160
177
 
168
185
            called directly. Only from RevisionSpec.from_string()
169
186
        """
170
187
        if not _internal:
171
 
            # XXX: Update this after 0.10 is released
172
188
            symbol_versioning.warn('Creating a RevisionSpec directly has'
173
189
                                   ' been deprecated in version 0.11. Use'
174
190
                                   ' RevisionSpec.from_string()'
181
197
 
182
198
    def _match_on(self, branch, revs):
183
199
        trace.mutter('Returning RevisionSpec._match_on: None')
184
 
        return RevisionInfo(branch, 0, None)
 
200
        return RevisionInfo(branch, None, None)
185
201
 
186
202
    def _match_on_and_check(self, branch, revs):
187
203
        info = self._match_on(branch, revs)
188
204
        if info:
189
205
            return info
190
 
        elif info == (0, None):
191
 
            # special case - the empty tree
 
206
        elif info == (None, None):
 
207
            # special case - nothing supplied
192
208
            return info
193
209
        elif self.prefix:
194
210
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
197
213
 
198
214
    def in_history(self, branch):
199
215
        if branch:
200
 
            revs = branch.revision_history()
 
216
            if self.wants_revision_history:
 
217
                revs = branch.revision_history()
 
218
            else:
 
219
                revs = None
201
220
        else:
 
221
            # this should never trigger.
 
222
            # TODO: make it a deprecated code path. RBC 20060928
202
223
            revs = None
203
224
        return self._match_on_and_check(branch, revs)
204
225
 
211
232
    # will do what you expect.
212
233
    in_store = in_history
213
234
    in_branch = in_store
214
 
        
 
235
 
 
236
    def as_revision_id(self, context_branch):
 
237
        """Return just the revision_id for this revisions spec.
 
238
 
 
239
        Some revision specs require a context_branch to be able to determine
 
240
        their value. Not all specs will make use of it.
 
241
        """
 
242
        return self._as_revision_id(context_branch)
 
243
 
 
244
    def _as_revision_id(self, context_branch):
 
245
        """Implementation of as_revision_id()
 
246
 
 
247
        Classes should override this function to provide appropriate
 
248
        functionality. The default is to just call '.in_history().rev_id'
 
249
        """
 
250
        return self.in_history(context_branch).rev_id
 
251
 
 
252
    def as_tree(self, context_branch):
 
253
        """Return the tree object for this revisions spec.
 
254
 
 
255
        Some revision specs require a context_branch to be able to determine
 
256
        the revision id and access the repository. Not all specs will make
 
257
        use of it.
 
258
        """
 
259
        return self._as_tree(context_branch)
 
260
 
 
261
    def _as_tree(self, context_branch):
 
262
        """Implementation of as_tree().
 
263
 
 
264
        Classes should override this function to provide appropriate
 
265
        functionality. The default is to just call '.as_revision_id()'
 
266
        and get the revision tree from context_branch's repository.
 
267
        """
 
268
        revision_id = self.as_revision_id(context_branch)
 
269
        return context_branch.repository.revision_tree(revision_id)
 
270
 
215
271
    def __repr__(self):
216
272
        # this is mostly for helping with testing
217
273
        return '<%s %s>' % (self.__class__.__name__,
218
274
                              self.user_spec)
219
 
    
 
275
 
220
276
    def needs_branch(self):
221
277
        """Whether this revision spec needs a branch.
222
278
 
226
282
 
227
283
    def get_branch(self):
228
284
        """When the revision specifier contains a branch location, return it.
229
 
        
 
285
 
230
286
        Otherwise, return None.
231
287
        """
232
288
        return None
235
291
# private API
236
292
 
237
293
class RevisionSpec_revno(RevisionSpec):
 
294
    """Selects a revision using a number."""
 
295
 
 
296
    help_txt = """Selects a revision using a number.
 
297
 
 
298
    Use an integer to specify a revision in the history of the branch.
 
299
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
300
    A negative number will count from the end of the branch (-1 is the
 
301
    last revision, -2 the previous one). If the negative number is larger
 
302
    than the branch's history, the first revision is returned.
 
303
    Examples::
 
304
 
 
305
      revno:1                   -> return the first revision of this branch
 
306
      revno:3:/path/to/branch   -> return the 3rd revision of
 
307
                                   the branch '/path/to/branch'
 
308
      revno:-1                  -> The last revision in a branch.
 
309
      -2:http://other/branch    -> The second to last revision in the
 
310
                                   remote branch.
 
311
      -1000000                  -> Most likely the first revision, unless
 
312
                                   your history is very long.
 
313
    """
238
314
    prefix = 'revno:'
 
315
    wants_revision_history = False
239
316
 
240
317
    def _match_on(self, branch, revs):
241
318
        """Lookup a revision by revision number"""
 
319
        branch, revno, revision_id = self._lookup(branch, revs)
 
320
        return RevisionInfo(branch, revno, revision_id)
 
321
 
 
322
    def _lookup(self, branch, revs_or_none):
242
323
        loc = self.spec.find(':')
243
324
        if loc == -1:
244
325
            revno_spec = self.spec
255
336
        else:
256
337
            try:
257
338
                revno = int(revno_spec)
258
 
            except ValueError, e:
259
 
                raise errors.InvalidRevisionSpec(self.user_spec,
260
 
                                                 branch, e)
 
339
                dotted = False
 
340
            except ValueError:
 
341
                # dotted decimal. This arguably should not be here
 
342
                # but the from_string method is a little primitive
 
343
                # right now - RBC 20060928
 
344
                try:
 
345
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
 
346
                except ValueError, e:
 
347
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
348
 
 
349
                dotted = True
261
350
 
262
351
        if branch_spec:
 
352
            # the user has override the branch to look in.
 
353
            # we need to refresh the revision_history map and
 
354
            # the branch object.
263
355
            from bzrlib.branch import Branch
264
356
            branch = Branch.open(branch_spec)
265
 
            # Need to use a new revision history
266
 
            # because we are using a specific branch
267
 
            revs = branch.revision_history()
 
357
            revs_or_none = None
268
358
 
269
 
        if revno < 0:
270
 
            if (-revno) >= len(revs):
271
 
                revno = 1
 
359
        if dotted:
 
360
            try:
 
361
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
 
362
                    _cache_reverse=True)
 
363
            except errors.NoSuchRevision:
 
364
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
272
365
            else:
273
 
                revno = len(revs) + revno + 1
274
 
        try:
275
 
            revision_id = branch.get_rev_id(revno, revs)
276
 
        except errors.NoSuchRevision:
277
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
278
 
        return RevisionInfo(branch, revno, revision_id)
279
 
        
 
366
                # there is no traditional 'revno' for dotted-decimal revnos.
 
367
                # so for  API compatability we return None.
 
368
                return branch, None, revision_id
 
369
        else:
 
370
            last_revno, last_revision_id = branch.last_revision_info()
 
371
            if revno < 0:
 
372
                # if get_rev_id supported negative revnos, there would not be a
 
373
                # need for this special case.
 
374
                if (-revno) >= last_revno:
 
375
                    revno = 1
 
376
                else:
 
377
                    revno = last_revno + revno + 1
 
378
            try:
 
379
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
380
            except errors.NoSuchRevision:
 
381
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
382
        return branch, revno, revision_id
 
383
 
 
384
    def _as_revision_id(self, context_branch):
 
385
        # We would have the revno here, but we don't really care
 
386
        branch, revno, revision_id = self._lookup(context_branch, None)
 
387
        return revision_id
 
388
 
280
389
    def needs_branch(self):
281
390
        return self.spec.find(':') == -1
282
391
 
286
395
        else:
287
396
            return self.spec[self.spec.find(':')+1:]
288
397
 
289
 
# Old compatibility 
 
398
# Old compatibility
290
399
RevisionSpec_int = RevisionSpec_revno
291
400
 
292
 
SPEC_TYPES.append(RevisionSpec_revno)
293
401
 
294
402
 
295
403
class RevisionSpec_revid(RevisionSpec):
 
404
    """Selects a revision using the revision id."""
 
405
 
 
406
    help_txt = """Selects a revision using the revision id.
 
407
 
 
408
    Supply a specific revision id, that can be used to specify any
 
409
    revision id in the ancestry of the branch.
 
410
    Including merges, and pending merges.
 
411
    Examples::
 
412
 
 
413
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
 
414
    """
 
415
 
296
416
    prefix = 'revid:'
297
417
 
298
418
    def _match_on(self, branch, revs):
299
 
        try:
300
 
            revno = revs.index(self.spec) + 1
301
 
        except ValueError:
302
 
            revno = None
303
 
        return RevisionInfo(branch, revno, self.spec)
304
 
 
305
 
SPEC_TYPES.append(RevisionSpec_revid)
 
419
        # self.spec comes straight from parsing the command line arguments,
 
420
        # so we expect it to be a Unicode string. Switch it to the internal
 
421
        # representation.
 
422
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
423
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
424
 
 
425
    def _as_revision_id(self, context_branch):
 
426
        return osutils.safe_revision_id(self.spec, warn=False)
 
427
 
306
428
 
307
429
 
308
430
class RevisionSpec_last(RevisionSpec):
 
431
    """Selects the nth revision from the end."""
 
432
 
 
433
    help_txt = """Selects the nth revision from the end.
 
434
 
 
435
    Supply a positive number to get the nth revision from the end.
 
436
    This is the same as supplying negative numbers to the 'revno:' spec.
 
437
    Examples::
 
438
 
 
439
      last:1        -> return the last revision
 
440
      last:3        -> return the revision 2 before the end.
 
441
    """
309
442
 
310
443
    prefix = 'last:'
311
444
 
312
445
    def _match_on(self, branch, revs):
 
446
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
447
        return RevisionInfo(branch, revno, revision_id)
 
448
 
 
449
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
450
        last_revno, last_revision_id = context_branch.last_revision_info()
 
451
 
313
452
        if self.spec == '':
314
 
            if not revs:
315
 
                raise errors.NoCommits(branch)
316
 
            return RevisionInfo(branch, len(revs), revs[-1])
 
453
            if not last_revno:
 
454
                raise errors.NoCommits(context_branch)
 
455
            return last_revno, last_revision_id
317
456
 
318
457
        try:
319
458
            offset = int(self.spec)
320
459
        except ValueError, e:
321
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
460
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
322
461
 
323
462
        if offset <= 0:
324
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
463
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
325
464
                                             'you must supply a positive value')
326
 
        revno = len(revs) - offset + 1
 
465
 
 
466
        revno = last_revno - offset + 1
327
467
        try:
328
 
            revision_id = branch.get_rev_id(revno, revs)
 
468
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
329
469
        except errors.NoSuchRevision:
330
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
331
 
        return RevisionInfo(branch, revno, revision_id)
332
 
 
333
 
SPEC_TYPES.append(RevisionSpec_last)
 
470
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
471
        return revno, revision_id
 
472
 
 
473
    def _as_revision_id(self, context_branch):
 
474
        # We compute the revno as part of the process, but we don't really care
 
475
        # about it.
 
476
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
477
        return revision_id
 
478
 
334
479
 
335
480
 
336
481
class RevisionSpec_before(RevisionSpec):
 
482
    """Selects the parent of the revision specified."""
 
483
 
 
484
    help_txt = """Selects the parent of the revision specified.
 
485
 
 
486
    Supply any revision spec to return the parent of that revision.  This is
 
487
    mostly useful when inspecting revisions that are not in the revision history
 
488
    of a branch.
 
489
 
 
490
    It is an error to request the parent of the null revision (before:0).
 
491
 
 
492
    Examples::
 
493
 
 
494
      before:1913    -> Return the parent of revno 1913 (revno 1912)
 
495
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
 
496
                                            aaaa@bbbb-1234567890
 
497
      bzr diff -r before:1913..1913
 
498
            -> Find the changes between revision 1913 and its parent (1912).
 
499
               (What changes did revision 1913 introduce).
 
500
               This is equivalent to:  bzr diff -c 1913
 
501
    """
337
502
 
338
503
    prefix = 'before:'
339
 
    
 
504
 
340
505
    def _match_on(self, branch, revs):
341
506
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
342
507
        if r.revno == 0:
347
512
            rev = branch.repository.get_revision(r.rev_id)
348
513
            if not rev.parent_ids:
349
514
                revno = 0
350
 
                revision_id = None
 
515
                revision_id = revision.NULL_REVISION
351
516
            else:
352
517
                revision_id = rev.parent_ids[0]
353
518
                try:
363
528
                                                 branch)
364
529
        return RevisionInfo(branch, revno, revision_id)
365
530
 
366
 
SPEC_TYPES.append(RevisionSpec_before)
 
531
    def _as_revision_id(self, context_branch):
 
532
        base_revspec = RevisionSpec.from_string(self.spec)
 
533
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
534
        if base_revision_id == revision.NULL_REVISION:
 
535
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
536
                                         'cannot go before the null: revision')
 
537
        context_repo = context_branch.repository
 
538
        context_repo.lock_read()
 
539
        try:
 
540
            parent_map = context_repo.get_parent_map([base_revision_id])
 
541
        finally:
 
542
            context_repo.unlock()
 
543
        if base_revision_id not in parent_map:
 
544
            # Ghost, or unknown revision id
 
545
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
546
                'cannot find the matching revision')
 
547
        parents = parent_map[base_revision_id]
 
548
        if len(parents) < 1:
 
549
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
550
                'No parents for revision.')
 
551
        return parents[0]
 
552
 
367
553
 
368
554
 
369
555
class RevisionSpec_tag(RevisionSpec):
 
556
    """Select a revision identified by tag name"""
 
557
 
 
558
    help_txt = """Selects a revision identified by a tag name.
 
559
 
 
560
    Tags are stored in the branch and created by the 'tag' command.
 
561
    """
 
562
 
370
563
    prefix = 'tag:'
371
564
 
372
565
    def _match_on(self, branch, revs):
373
 
        raise errors.InvalidRevisionSpec(self.user_spec, branch,
374
 
                                         'tag: namespace registered,'
375
 
                                         ' but not implemented')
376
 
 
377
 
SPEC_TYPES.append(RevisionSpec_tag)
 
566
        # Can raise tags not supported, NoSuchTag, etc
 
567
        return RevisionInfo.from_revision_id(branch,
 
568
            branch.tags.lookup_tag(self.spec),
 
569
            revs)
 
570
 
 
571
    def _as_revision_id(self, context_branch):
 
572
        return context_branch.tags.lookup_tag(self.spec)
 
573
 
378
574
 
379
575
 
380
576
class _RevListToTimestamps(object):
397
593
 
398
594
 
399
595
class RevisionSpec_date(RevisionSpec):
 
596
    """Selects a revision on the basis of a datestamp."""
 
597
 
 
598
    help_txt = """Selects a revision on the basis of a datestamp.
 
599
 
 
600
    Supply a datestamp to select the first revision that matches the date.
 
601
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
602
    Matches the first entry after a given date (either at midnight or
 
603
    at a specified time).
 
604
 
 
605
    One way to display all the changes since yesterday would be::
 
606
 
 
607
        bzr log -r date:yesterday..
 
608
 
 
609
    Examples::
 
610
 
 
611
      date:yesterday            -> select the first revision since yesterday
 
612
      date:2006-08-14,17:10:14  -> select the first revision after
 
613
                                   August 14th, 2006 at 5:10pm.
 
614
    """
400
615
    prefix = 'date:'
401
616
    _date_re = re.compile(
402
617
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
405
620
        )
406
621
 
407
622
    def _match_on(self, branch, revs):
408
 
        """
409
 
        Spec for date revisions:
 
623
        """Spec for date revisions:
410
624
          date:value
411
625
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
412
626
          matches the first entry after a given date (either at midnight or
413
627
          at a specified time).
414
 
 
415
 
          So the proper way of saying 'give me all entries for today' is:
416
 
              -r date:yesterday..date:today
417
628
        """
 
629
        #  XXX: This doesn't actually work
 
630
        #  So the proper way of saying 'give me all entries for today' is:
 
631
        #      -r date:yesterday..date:today
418
632
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
419
633
        if self.spec.lower() == 'yesterday':
420
634
            dt = today - datetime.timedelta(days=1)
459
673
        finally:
460
674
            branch.unlock()
461
675
        if rev == len(revs):
462
 
            return RevisionInfo(branch, None)
 
676
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
463
677
        else:
464
678
            return RevisionInfo(branch, rev + 1)
465
679
 
466
 
SPEC_TYPES.append(RevisionSpec_date)
467
680
 
468
681
 
469
682
class RevisionSpec_ancestor(RevisionSpec):
 
683
    """Selects a common ancestor with a second branch."""
 
684
 
 
685
    help_txt = """Selects a common ancestor with a second branch.
 
686
 
 
687
    Supply the path to a branch to select the common ancestor.
 
688
 
 
689
    The common ancestor is the last revision that existed in both
 
690
    branches. Usually this is the branch point, but it could also be
 
691
    a revision that was merged.
 
692
 
 
693
    This is frequently used with 'diff' to return all of the changes
 
694
    that your branch introduces, while excluding the changes that you
 
695
    have not merged from the remote branch.
 
696
 
 
697
    Examples::
 
698
 
 
699
      ancestor:/path/to/branch
 
700
      $ bzr diff -r ancestor:../../mainline/branch
 
701
    """
470
702
    prefix = 'ancestor:'
471
703
 
472
704
    def _match_on(self, branch, revs):
473
 
        from bzrlib.branch import Branch
474
 
 
475
705
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
476
 
        other_branch = Branch.open(self.spec)
477
 
        revision_a = branch.last_revision()
478
 
        revision_b = other_branch.last_revision()
479
 
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
480
 
            if r in (None, revision.NULL_REVISION):
481
 
                raise errors.NoCommits(b)
482
 
        revision_source = revision.MultipleRevisionSources(
483
 
                branch.repository, other_branch.repository)
484
 
        rev_id = revision.common_ancestor(revision_a, revision_b,
485
 
                                          revision_source)
 
706
        return self._find_revision_info(branch, self.spec)
 
707
 
 
708
    def _as_revision_id(self, context_branch):
 
709
        return self._find_revision_id(context_branch, self.spec)
 
710
 
 
711
    @staticmethod
 
712
    def _find_revision_info(branch, other_location):
 
713
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
 
714
                                                              other_location)
486
715
        try:
487
 
            revno = branch.revision_id_to_revno(rev_id)
 
716
            revno = branch.revision_id_to_revno(revision_id)
488
717
        except errors.NoSuchRevision:
489
718
            revno = None
490
 
        return RevisionInfo(branch, revno, rev_id)
491
 
        
492
 
SPEC_TYPES.append(RevisionSpec_ancestor)
 
719
        return RevisionInfo(branch, revno, revision_id)
 
720
 
 
721
    @staticmethod
 
722
    def _find_revision_id(branch, other_location):
 
723
        from bzrlib.branch import Branch
 
724
 
 
725
        branch.lock_read()
 
726
        try:
 
727
            revision_a = revision.ensure_null(branch.last_revision())
 
728
            if revision_a == revision.NULL_REVISION:
 
729
                raise errors.NoCommits(branch)
 
730
            if other_location == '':
 
731
                other_location = branch.get_parent()
 
732
            other_branch = Branch.open(other_location)
 
733
            other_branch.lock_read()
 
734
            try:
 
735
                revision_b = revision.ensure_null(other_branch.last_revision())
 
736
                if revision_b == revision.NULL_REVISION:
 
737
                    raise errors.NoCommits(other_branch)
 
738
                graph = branch.repository.get_graph(other_branch.repository)
 
739
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
740
            finally:
 
741
                other_branch.unlock()
 
742
            if rev_id == revision.NULL_REVISION:
 
743
                raise errors.NoCommonAncestor(revision_a, revision_b)
 
744
            return rev_id
 
745
        finally:
 
746
            branch.unlock()
 
747
 
 
748
 
493
749
 
494
750
 
495
751
class RevisionSpec_branch(RevisionSpec):
496
 
    """A branch: revision specifier.
497
 
 
498
 
    This takes the path to a branch and returns its tip revision id.
 
752
    """Selects the last revision of a specified branch."""
 
753
 
 
754
    help_txt = """Selects the last revision of a specified branch.
 
755
 
 
756
    Supply the path to a branch to select its last revision.
 
757
 
 
758
    Examples::
 
759
 
 
760
      branch:/path/to/branch
499
761
    """
500
762
    prefix = 'branch:'
501
763
 
512
774
        except errors.NoSuchRevision:
513
775
            revno = None
514
776
        return RevisionInfo(branch, revno, revision_b)
515
 
        
516
 
SPEC_TYPES.append(RevisionSpec_branch)
 
777
 
 
778
    def _as_revision_id(self, context_branch):
 
779
        from bzrlib.branch import Branch
 
780
        other_branch = Branch.open(self.spec)
 
781
        last_revision = other_branch.last_revision()
 
782
        last_revision = revision.ensure_null(last_revision)
 
783
        context_branch.fetch(other_branch, last_revision)
 
784
        if last_revision == revision.NULL_REVISION:
 
785
            raise errors.NoCommits(other_branch)
 
786
        return last_revision
 
787
 
 
788
    def _as_tree(self, context_branch):
 
789
        from bzrlib.branch import Branch
 
790
        other_branch = Branch.open(self.spec)
 
791
        last_revision = other_branch.last_revision()
 
792
        last_revision = revision.ensure_null(last_revision)
 
793
        if last_revision == revision.NULL_REVISION:
 
794
            raise errors.NoCommits(other_branch)
 
795
        return other_branch.repository.revision_tree(last_revision)
 
796
 
 
797
 
 
798
 
 
799
class RevisionSpec_submit(RevisionSpec_ancestor):
 
800
    """Selects a common ancestor with a submit branch."""
 
801
 
 
802
    help_txt = """Selects a common ancestor with the submit branch.
 
803
 
 
804
    Diffing against this shows all the changes that were made in this branch,
 
805
    and is a good predictor of what merge will do.  The submit branch is
 
806
    used by the bundle and merge directive commands.  If no submit branch
 
807
    is specified, the parent branch is used instead.
 
808
 
 
809
    The common ancestor is the last revision that existed in both
 
810
    branches. Usually this is the branch point, but it could also be
 
811
    a revision that was merged.
 
812
 
 
813
    Examples::
 
814
 
 
815
      $ bzr diff -r submit:
 
816
    """
 
817
 
 
818
    prefix = 'submit:'
 
819
 
 
820
    def _get_submit_location(self, branch):
 
821
        submit_location = branch.get_submit_branch()
 
822
        location_type = 'submit branch'
 
823
        if submit_location is None:
 
824
            submit_location = branch.get_parent()
 
825
            location_type = 'parent branch'
 
826
        if submit_location is None:
 
827
            raise errors.NoSubmitBranch(branch)
 
828
        trace.note('Using %s %s', location_type, submit_location)
 
829
        return submit_location
 
830
 
 
831
    def _match_on(self, branch, revs):
 
832
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
833
        return self._find_revision_info(branch,
 
834
            self._get_submit_location(branch))
 
835
 
 
836
    def _as_revision_id(self, context_branch):
 
837
        return self._find_revision_id(context_branch,
 
838
            self._get_submit_location(context_branch))
 
839
 
 
840
 
 
841
revspec_registry = registry.Registry()
 
842
def _register_revspec(revspec):
 
843
    revspec_registry.register(revspec.prefix, revspec)
 
844
 
 
845
_register_revspec(RevisionSpec_revno)
 
846
_register_revspec(RevisionSpec_revid)
 
847
_register_revspec(RevisionSpec_last)
 
848
_register_revspec(RevisionSpec_before)
 
849
_register_revspec(RevisionSpec_tag)
 
850
_register_revspec(RevisionSpec_date)
 
851
_register_revspec(RevisionSpec_ancestor)
 
852
_register_revspec(RevisionSpec_branch)
 
853
_register_revspec(RevisionSpec_submit)
 
854
 
 
855
SPEC_TYPES = symbol_versioning.deprecated_list(
 
856
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])