/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: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
 
 
20
 
from .lazy_import import lazy_import
 
17
 
 
18
import re
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
21
21
lazy_import(globals(), """
22
22
import bisect
23
23
import datetime
24
 
 
25
 
from breezy import (
26
 
    branch as _mod_branch,
27
 
    cache_utf8,
28
 
    revision,
29
 
    workingtree,
30
 
    )
31
 
from breezy.i18n import gettext
32
24
""")
33
25
 
34
 
from . import (
 
26
from bzrlib import (
35
27
    errors,
36
 
    lazy_regex,
 
28
    osutils,
37
29
    registry,
 
30
    revision,
 
31
    symbol_versioning,
38
32
    trace,
39
33
    )
40
 
from .sixish import (
41
 
    text_type,
42
 
    )
 
34
 
 
35
 
 
36
_marker = []
43
37
 
44
38
 
45
39
class RevisionInfo(object):
59
53
    or treat the result as a tuple.
60
54
    """
61
55
 
62
 
    def __init__(self, branch, revno=None, rev_id=None):
 
56
    def __init__(self, branch, revno, rev_id=_marker):
63
57
        self.branch = branch
64
 
        self._has_revno = (revno is not None)
65
 
        self._revno = revno
66
 
        self.rev_id = rev_id
67
 
        if self.rev_id is None and self._revno is not None:
 
58
        self.revno = revno
 
59
        if rev_id is _marker:
68
60
            # allow caller to be lazy
69
 
            self.rev_id = branch.get_rev_id(self._revno)
70
 
 
71
 
    @property
72
 
    def revno(self):
73
 
        if not self._has_revno and self.rev_id is not None:
74
 
            try:
75
 
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
76
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
77
 
                self._revno = None
78
 
            self._has_revno = True
79
 
        return self._revno
80
 
 
81
 
    def __bool__(self):
 
61
            if self.revno is None:
 
62
                self.rev_id = None
 
63
            else:
 
64
                self.rev_id = branch.get_rev_id(self.revno)
 
65
        else:
 
66
            self.rev_id = rev_id
 
67
 
 
68
    def __nonzero__(self):
 
69
        # first the easy ones...
82
70
        if self.rev_id is None:
83
71
            return False
 
72
        if self.revno is not None:
 
73
            return True
84
74
        # TODO: otherwise, it should depend on how I was built -
85
75
        # if it's in_history(branch), then check revision_history(),
86
76
        # if it's in_store(branch), do the check below
87
77
        return self.branch.repository.has_revision(self.rev_id)
88
78
 
89
 
    __nonzero__ = __bool__
90
 
 
91
79
    def __len__(self):
92
80
        return 2
93
81
 
94
82
    def __getitem__(self, index):
95
 
        if index == 0:
96
 
            return self.revno
97
 
        if index == 1:
98
 
            return self.rev_id
 
83
        if index == 0: return self.revno
 
84
        if index == 1: return self.rev_id
99
85
        raise IndexError(index)
100
86
 
101
87
    def get(self):
104
90
    def __eq__(self, other):
105
91
        if type(other) not in (tuple, list, type(self)):
106
92
            return False
107
 
        if isinstance(other, type(self)) and self.branch is not other.branch:
 
93
        if type(other) is type(self) and self.branch is not other.branch:
108
94
            return False
109
95
        return tuple(self) == tuple(other)
110
96
 
111
97
    def __repr__(self):
112
 
        return '<breezy.revisionspec.RevisionInfo object %s, %s for %r>' % (
 
98
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
113
99
            self.revno, self.rev_id, self.branch)
114
100
 
115
101
    @staticmethod
116
 
    def from_revision_id(branch, revision_id):
 
102
    def from_revision_id(branch, revision_id, revs):
117
103
        """Construct a RevisionInfo given just the id.
118
104
 
119
105
        Use this if you don't know or care what the revno is.
120
106
        """
121
 
        return RevisionInfo(branch, revno=None, rev_id=revision_id)
 
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
 
 
115
 
 
116
_revno_regex = None
122
117
 
123
118
 
124
119
class RevisionSpec(object):
141
136
    """
142
137
 
143
138
    prefix = None
 
139
    wants_revision_history = True
144
140
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
145
141
    """Exceptions that RevisionSpec_dwim._match_on will catch.
146
142
 
158
154
        :return: A RevisionSpec object that understands how to parse the
159
155
            supplied notation.
160
156
        """
 
157
        if not isinstance(spec, (type(None), basestring)):
 
158
            raise TypeError('error')
 
159
 
161
160
        if spec is None:
162
161
            return RevisionSpec(None, _internal=True)
163
 
        if not isinstance(spec, (str, text_type)):
164
 
            raise TypeError("revision spec needs to be text")
165
162
        match = revspec_registry.get_prefix(spec)
166
163
        if match is not None:
167
164
            spectype, specsuffix = match
169
166
                         spectype.__name__, spec)
170
167
            return spectype(spec, _internal=True)
171
168
        else:
 
169
            for spectype in SPEC_TYPES:
 
170
                if spec.startswith(spectype.prefix):
 
171
                    trace.mutter('Returning RevisionSpec %s for %s',
 
172
                                 spectype.__name__, spec)
 
173
                    return spectype(spec, _internal=True)
172
174
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
173
175
            # wait for _match_on to be called.
174
176
            return RevisionSpec_dwim(spec, _internal=True)
181
183
            called directly. Only from RevisionSpec.from_string()
182
184
        """
183
185
        if not _internal:
184
 
            raise AssertionError(
185
 
                'Creating a RevisionSpec directly is not supported. '
186
 
                'Use RevisionSpec.from_string() instead.')
 
186
            symbol_versioning.warn('Creating a RevisionSpec directly has'
 
187
                                   ' been deprecated in version 0.11. Use'
 
188
                                   ' RevisionSpec.from_string()'
 
189
                                   ' instead.',
 
190
                                   DeprecationWarning, stacklevel=2)
187
191
        self.user_spec = spec
188
192
        if self.prefix and spec.startswith(self.prefix):
189
193
            spec = spec[len(self.prefix):]
206
210
            raise errors.InvalidRevisionSpec(self.spec, branch)
207
211
 
208
212
    def in_history(self, branch):
209
 
        return self._match_on_and_check(branch, revs=None)
 
213
        if branch:
 
214
            if self.wants_revision_history:
 
215
                revs = branch.revision_history()
 
216
            else:
 
217
                revs = None
 
218
        else:
 
219
            # this should never trigger.
 
220
            # TODO: make it a deprecated code path. RBC 20060928
 
221
            revs = None
 
222
        return self._match_on_and_check(branch, revs)
210
223
 
211
224
        # FIXME: in_history is somewhat broken,
212
225
        # it will return non-history revisions in many
256
269
    def __repr__(self):
257
270
        # this is mostly for helping with testing
258
271
        return '<%s %s>' % (self.__class__.__name__,
259
 
                            self.user_spec)
 
272
                              self.user_spec)
260
273
 
261
274
    def needs_branch(self):
262
275
        """Whether this revision spec needs a branch.
285
298
    """
286
299
 
287
300
    help_txt = None
288
 
 
289
 
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
290
 
 
291
 
    # The revspecs to try
292
 
    _possible_revspecs = []
 
301
    # We don't need to build the revision history ourself, that's delegated to
 
302
    # each revspec we try.
 
303
    wants_revision_history = False
293
304
 
294
305
    def _try_spectype(self, rstype, branch):
295
306
        rs = rstype(self.spec, _internal=True)
301
312
        """Run the lookup and see what we can get."""
302
313
 
303
314
        # First, see if it's a revno
304
 
        if self._revno_regex.match(self.spec) is not None:
 
315
        global _revno_regex
 
316
        if _revno_regex is None:
 
317
            _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
318
        if _revno_regex.match(self.spec) is not None:
305
319
            try:
306
320
                return self._try_spectype(RevisionSpec_revno, branch)
307
321
            except RevisionSpec_revno.dwim_catchable_exceptions:
308
322
                pass
309
323
 
310
324
        # Next see what has been registered
311
 
        for objgetter in self._possible_revspecs:
312
 
            rs_class = objgetter.get_obj()
 
325
        for rs_class in dwim_revspecs:
313
326
            try:
314
327
                return self._try_spectype(rs_class, branch)
315
328
            except rs_class.dwim_catchable_exceptions:
320
333
        # really relevant.
321
334
        raise errors.InvalidRevisionSpec(self.spec, branch)
322
335
 
323
 
    @classmethod
324
 
    def append_possible_revspec(cls, revspec):
325
 
        """Append a possible DWIM revspec.
326
 
 
327
 
        :param revspec: Revision spec to try.
328
 
        """
329
 
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
330
 
 
331
 
    @classmethod
332
 
    def append_possible_lazy_revspec(cls, module_name, member_name):
333
 
        """Append a possible lazily loaded DWIM revspec.
334
 
 
335
 
        :param module_name: Name of the module with the revspec
336
 
        :param member_name: Name of the revspec within the module
337
 
        """
338
 
        cls._possible_revspecs.append(
339
 
            registry._LazyObjectGetter(module_name, member_name))
340
 
 
341
336
 
342
337
class RevisionSpec_revno(RevisionSpec):
343
338
    """Selects a revision using a number."""
361
356
                                   your history is very long.
362
357
    """
363
358
    prefix = 'revno:'
 
359
    wants_revision_history = False
364
360
 
365
361
    def _match_on(self, branch, revs):
366
362
        """Lookup a revision by revision number"""
367
 
        branch, revno, revision_id = self._lookup(branch)
 
363
        branch, revno, revision_id = self._lookup(branch, revs)
368
364
        return RevisionInfo(branch, revno, revision_id)
369
365
 
370
 
    def _lookup(self, branch):
 
366
    def _lookup(self, branch, revs_or_none):
371
367
        loc = self.spec.find(':')
372
368
        if loc == -1:
373
369
            revno_spec = self.spec
374
370
            branch_spec = None
375
371
        else:
376
372
            revno_spec = self.spec[:loc]
377
 
            branch_spec = self.spec[loc + 1:]
 
373
            branch_spec = self.spec[loc+1:]
378
374
 
379
375
        if revno_spec == '':
380
376
            if not branch_spec:
381
377
                raise errors.InvalidRevisionSpec(self.user_spec,
382
 
                                                 branch, 'cannot have an empty revno and no branch')
 
378
                        branch, 'cannot have an empty revno and no branch')
383
379
            revno = None
384
380
        else:
385
381
            try:
390
386
                # but the from_string method is a little primitive
391
387
                # right now - RBC 20060928
392
388
                try:
393
 
                    match_revno = tuple((int(number)
394
 
                                         for number in revno_spec.split('.')))
395
 
                except ValueError as e:
 
389
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
 
390
                except ValueError, e:
396
391
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
397
392
 
398
393
                dotted = True
399
394
 
400
395
        if branch_spec:
401
 
            # the user has overriden the branch to look in.
402
 
            branch = _mod_branch.Branch.open(branch_spec)
 
396
            # the user has override the branch to look in.
 
397
            # we need to refresh the revision_history map and
 
398
            # the branch object.
 
399
            from bzrlib.branch import Branch
 
400
            branch = Branch.open(branch_spec)
 
401
            revs_or_none = None
403
402
 
404
403
        if dotted:
405
404
            try:
406
405
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
407
 
                                                                 _cache_reverse=True)
408
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
406
                    _cache_reverse=True)
 
407
            except errors.NoSuchRevision:
409
408
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
410
409
            else:
411
410
                # there is no traditional 'revno' for dotted-decimal revnos.
412
 
                # so for API compatibility we return None.
 
411
                # so for  API compatability we return None.
413
412
                return branch, None, revision_id
414
413
        else:
415
414
            last_revno, last_revision_id = branch.last_revision_info()
421
420
                else:
422
421
                    revno = last_revno + revno + 1
423
422
            try:
424
 
                revision_id = branch.get_rev_id(revno)
425
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
423
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
424
            except errors.NoSuchRevision:
426
425
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
427
426
        return branch, revno, revision_id
428
427
 
429
428
    def _as_revision_id(self, context_branch):
430
429
        # We would have the revno here, but we don't really care
431
 
        branch, revno, revision_id = self._lookup(context_branch)
 
430
        branch, revno, revision_id = self._lookup(context_branch, None)
432
431
        return revision_id
433
432
 
434
433
    def needs_branch(self):
438
437
        if self.spec.find(':') == -1:
439
438
            return None
440
439
        else:
441
 
            return self.spec[self.spec.find(':') + 1:]
442
 
 
 
440
            return self.spec[self.spec.find(':')+1:]
443
441
 
444
442
# Old compatibility
445
443
RevisionSpec_int = RevisionSpec_revno
446
444
 
447
445
 
448
 
class RevisionIDSpec(RevisionSpec):
449
 
 
450
 
    def _match_on(self, branch, revs):
451
 
        revision_id = self.as_revision_id(branch)
452
 
        return RevisionInfo.from_revision_id(branch, revision_id)
453
 
 
454
 
 
455
 
class RevisionSpec_revid(RevisionIDSpec):
 
446
 
 
447
class RevisionSpec_revid(RevisionSpec):
456
448
    """Selects a revision using the revision id."""
457
449
 
458
450
    help_txt = """Selects a revision using the revision id.
467
459
 
468
460
    prefix = 'revid:'
469
461
 
470
 
    def _as_revision_id(self, context_branch):
 
462
    def _match_on(self, branch, revs):
471
463
        # self.spec comes straight from parsing the command line arguments,
472
464
        # so we expect it to be a Unicode string. Switch it to the internal
473
465
        # representation.
474
 
        if isinstance(self.spec, text_type):
475
 
            return cache_utf8.encode(self.spec)
476
 
        return self.spec
 
466
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
467
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
468
 
 
469
    def _as_revision_id(self, context_branch):
 
470
        return osutils.safe_revision_id(self.spec, warn=False)
 
471
 
477
472
 
478
473
 
479
474
class RevisionSpec_last(RevisionSpec):
492
487
    prefix = 'last:'
493
488
 
494
489
    def _match_on(self, branch, revs):
495
 
        revno, revision_id = self._revno_and_revision_id(branch)
 
490
        revno, revision_id = self._revno_and_revision_id(branch, revs)
496
491
        return RevisionInfo(branch, revno, revision_id)
497
492
 
498
 
    def _revno_and_revision_id(self, context_branch):
 
493
    def _revno_and_revision_id(self, context_branch, revs_or_none):
499
494
        last_revno, last_revision_id = context_branch.last_revision_info()
500
495
 
501
496
        if self.spec == '':
505
500
 
506
501
        try:
507
502
            offset = int(self.spec)
508
 
        except ValueError as e:
 
503
        except ValueError, e:
509
504
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
510
505
 
511
506
        if offset <= 0:
514
509
 
515
510
        revno = last_revno - offset + 1
516
511
        try:
517
 
            revision_id = context_branch.get_rev_id(revno)
518
 
        except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
512
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
 
513
        except errors.NoSuchRevision:
519
514
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
520
515
        return revno, revision_id
521
516
 
522
517
    def _as_revision_id(self, context_branch):
523
518
        # We compute the revno as part of the process, but we don't really care
524
519
        # about it.
525
 
        revno, revision_id = self._revno_and_revision_id(context_branch)
 
520
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
526
521
        return revision_id
527
522
 
528
523
 
 
524
 
529
525
class RevisionSpec_before(RevisionSpec):
530
526
    """Selects the parent of the revision specified."""
531
527
 
554
550
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
555
551
        if r.revno == 0:
556
552
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
557
 
                                             'cannot go before the null: revision')
 
553
                                         'cannot go before the null: revision')
558
554
        if r.revno is None:
559
555
            # We need to use the repository history here
560
556
            rev = branch.repository.get_revision(r.rev_id)
561
557
            if not rev.parent_ids:
 
558
                revno = 0
562
559
                revision_id = revision.NULL_REVISION
563
560
            else:
564
561
                revision_id = rev.parent_ids[0]
565
 
            revno = None
 
562
                try:
 
563
                    revno = revs.index(revision_id) + 1
 
564
                except ValueError:
 
565
                    revno = None
566
566
        else:
567
567
            revno = r.revno - 1
568
568
            try:
569
569
                revision_id = branch.get_rev_id(revno, revs)
570
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
570
            except errors.NoSuchRevision:
571
571
                raise errors.InvalidRevisionSpec(self.user_spec,
572
572
                                                 branch)
573
573
        return RevisionInfo(branch, revno, revision_id)
574
574
 
575
575
    def _as_revision_id(self, context_branch):
576
 
        base_revision_id = RevisionSpec.from_string(
577
 
            self.spec)._as_revision_id(context_branch)
 
576
        base_revspec = RevisionSpec.from_string(self.spec)
 
577
        base_revision_id = base_revspec.as_revision_id(context_branch)
578
578
        if base_revision_id == revision.NULL_REVISION:
579
579
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
580
 
                                             'cannot go before the null: revision')
 
580
                                         'cannot go before the null: revision')
581
581
        context_repo = context_branch.repository
582
 
        with context_repo.lock_read():
 
582
        context_repo.lock_read()
 
583
        try:
583
584
            parent_map = context_repo.get_parent_map([base_revision_id])
 
585
        finally:
 
586
            context_repo.unlock()
584
587
        if base_revision_id not in parent_map:
585
588
            # Ghost, or unknown revision id
586
589
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
587
 
                                             'cannot find the matching revision')
 
590
                'cannot find the matching revision')
588
591
        parents = parent_map[base_revision_id]
589
592
        if len(parents) < 1:
590
593
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
591
 
                                             'No parents for revision.')
 
594
                'No parents for revision.')
592
595
        return parents[0]
593
596
 
594
597
 
 
598
 
595
599
class RevisionSpec_tag(RevisionSpec):
596
600
    """Select a revision identified by tag name"""
597
601
 
606
610
    def _match_on(self, branch, revs):
607
611
        # Can raise tags not supported, NoSuchTag, etc
608
612
        return RevisionInfo.from_revision_id(branch,
609
 
                                             branch.tags.lookup_tag(self.spec))
 
613
            branch.tags.lookup_tag(self.spec),
 
614
            revs)
610
615
 
611
616
    def _as_revision_id(self, context_branch):
612
617
        return context_branch.tags.lookup_tag(self.spec)
613
618
 
614
619
 
 
620
 
615
621
class _RevListToTimestamps(object):
616
622
    """This takes a list of revisions, and allows you to bisect by date"""
617
623
 
618
 
    __slots__ = ['branch']
 
624
    __slots__ = ['revs', 'branch']
619
625
 
620
 
    def __init__(self, branch):
 
626
    def __init__(self, revs, branch):
 
627
        self.revs = revs
621
628
        self.branch = branch
622
629
 
623
630
    def __getitem__(self, index):
624
631
        """Get the date of the index'd item"""
625
 
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
 
632
        r = self.branch.repository.get_revision(self.revs[index])
626
633
        # TODO: Handle timezone.
627
634
        return datetime.datetime.fromtimestamp(r.timestamp)
628
635
 
629
636
    def __len__(self):
630
 
        return self.branch.revno()
 
637
        return len(self.revs)
631
638
 
632
639
 
633
640
class RevisionSpec_date(RevisionSpec):
642
649
 
643
650
    One way to display all the changes since yesterday would be::
644
651
 
645
 
        brz log -r date:yesterday..
 
652
        bzr log -r date:yesterday..
646
653
 
647
654
    Examples::
648
655
 
651
658
                                   August 14th, 2006 at 5:10pm.
652
659
    """
653
660
    prefix = 'date:'
654
 
    _date_regex = lazy_regex.lazy_compile(
655
 
        r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
656
 
        r'(,|T)?\s*'
657
 
        r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
661
    _date_re = re.compile(
 
662
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
663
            r'(,|T)?\s*'
 
664
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
658
665
        )
659
666
 
660
667
    def _match_on(self, branch, revs):
667
674
        #  XXX: This doesn't actually work
668
675
        #  So the proper way of saying 'give me all entries for today' is:
669
676
        #      -r date:yesterday..date:today
670
 
        today = datetime.datetime.fromordinal(
671
 
            datetime.date.today().toordinal())
 
677
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
672
678
        if self.spec.lower() == 'yesterday':
673
679
            dt = today - datetime.timedelta(days=1)
674
680
        elif self.spec.lower() == 'today':
676
682
        elif self.spec.lower() == 'tomorrow':
677
683
            dt = today + datetime.timedelta(days=1)
678
684
        else:
679
 
            m = self._date_regex.match(self.spec)
 
685
            m = self._date_re.match(self.spec)
680
686
            if not m or (not m.group('date') and not m.group('time')):
681
687
                raise errors.InvalidRevisionSpec(self.user_spec,
682
688
                                                 branch, 'invalid date')
699
705
                    else:
700
706
                        second = 0
701
707
                else:
702
 
                    hour, minute, second = 0, 0, 0
 
708
                    hour, minute, second = 0,0,0
703
709
            except ValueError:
704
710
                raise errors.InvalidRevisionSpec(self.user_spec,
705
711
                                                 branch, 'invalid date')
706
712
 
707
713
            dt = datetime.datetime(year=year, month=month, day=day,
708
 
                                   hour=hour, minute=minute, second=second)
709
 
        with branch.lock_read():
710
 
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
711
 
        if rev == branch.revno():
 
714
                    hour=hour, minute=minute, second=second)
 
715
        branch.lock_read()
 
716
        try:
 
717
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
718
        finally:
 
719
            branch.unlock()
 
720
        if rev == len(revs):
712
721
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
713
 
        return RevisionInfo(branch, rev)
 
722
        else:
 
723
            return RevisionInfo(branch, rev + 1)
 
724
 
714
725
 
715
726
 
716
727
class RevisionSpec_ancestor(RevisionSpec):
746
757
    def _find_revision_info(branch, other_location):
747
758
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
748
759
                                                              other_location)
749
 
        return RevisionInfo(branch, None, revision_id)
 
760
        try:
 
761
            revno = branch.revision_id_to_revno(revision_id)
 
762
        except errors.NoSuchRevision:
 
763
            revno = None
 
764
        return RevisionInfo(branch, revno, revision_id)
750
765
 
751
766
    @staticmethod
752
767
    def _find_revision_id(branch, other_location):
753
 
        from .branch import Branch
 
768
        from bzrlib.branch import Branch
754
769
 
755
 
        with branch.lock_read():
 
770
        branch.lock_read()
 
771
        try:
756
772
            revision_a = revision.ensure_null(branch.last_revision())
757
773
            if revision_a == revision.NULL_REVISION:
758
774
                raise errors.NoCommits(branch)
759
775
            if other_location == '':
760
776
                other_location = branch.get_parent()
761
777
            other_branch = Branch.open(other_location)
762
 
            with other_branch.lock_read():
 
778
            other_branch.lock_read()
 
779
            try:
763
780
                revision_b = revision.ensure_null(other_branch.last_revision())
764
781
                if revision_b == revision.NULL_REVISION:
765
782
                    raise errors.NoCommits(other_branch)
766
783
                graph = branch.repository.get_graph(other_branch.repository)
767
784
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
785
            finally:
 
786
                other_branch.unlock()
768
787
            if rev_id == revision.NULL_REVISION:
769
788
                raise errors.NoCommonAncestor(revision_a, revision_b)
770
789
            return rev_id
 
790
        finally:
 
791
            branch.unlock()
 
792
 
 
793
 
771
794
 
772
795
 
773
796
class RevisionSpec_branch(RevisionSpec):
785
808
    dwim_catchable_exceptions = (errors.NotBranchError,)
786
809
 
787
810
    def _match_on(self, branch, revs):
788
 
        from .branch import Branch
 
811
        from bzrlib.branch import Branch
789
812
        other_branch = Branch.open(self.spec)
790
813
        revision_b = other_branch.last_revision()
791
814
        if revision_b in (None, revision.NULL_REVISION):
798
821
                branch.fetch(other_branch, revision_b)
799
822
            except errors.ReadOnlyError:
800
823
                branch = other_branch
801
 
        return RevisionInfo(branch, None, revision_b)
 
824
        try:
 
825
            revno = branch.revision_id_to_revno(revision_b)
 
826
        except errors.NoSuchRevision:
 
827
            revno = None
 
828
        return RevisionInfo(branch, revno, revision_b)
802
829
 
803
830
    def _as_revision_id(self, context_branch):
804
 
        from .branch import Branch
 
831
        from bzrlib.branch import Branch
805
832
        other_branch = Branch.open(self.spec)
806
833
        last_revision = other_branch.last_revision()
807
834
        last_revision = revision.ensure_null(last_revision)
811
838
        return last_revision
812
839
 
813
840
    def _as_tree(self, context_branch):
814
 
        from .branch import Branch
 
841
        from bzrlib.branch import Branch
815
842
        other_branch = Branch.open(self.spec)
816
843
        last_revision = other_branch.last_revision()
817
844
        last_revision = revision.ensure_null(last_revision)
826
853
        return self.spec
827
854
 
828
855
 
 
856
 
829
857
class RevisionSpec_submit(RevisionSpec_ancestor):
830
858
    """Selects a common ancestor with a submit branch."""
831
859
 
855
883
            location_type = 'parent branch'
856
884
        if submit_location is None:
857
885
            raise errors.NoSubmitBranch(branch)
858
 
        trace.note(gettext('Using {0} {1}').format(location_type,
859
 
                                                   submit_location))
 
886
        trace.note('Using %s %s', location_type, submit_location)
860
887
        return submit_location
861
888
 
862
889
    def _match_on(self, branch, revs):
863
890
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
864
891
        return self._find_revision_info(branch,
865
 
                                        self._get_submit_location(branch))
 
892
            self._get_submit_location(branch))
866
893
 
867
894
    def _as_revision_id(self, context_branch):
868
895
        return self._find_revision_id(context_branch,
869
 
                                      self._get_submit_location(context_branch))
870
 
 
871
 
 
872
 
class RevisionSpec_annotate(RevisionIDSpec):
873
 
 
874
 
    prefix = 'annotate:'
875
 
 
876
 
    help_txt = """Select the revision that last modified the specified line.
877
 
 
878
 
    Select the revision that last modified the specified line.  Line is
879
 
    specified as path:number.  Path is a relative path to the file.  Numbers
880
 
    start at 1, and are relative to the current version, not the last-
881
 
    committed version of the file.
882
 
    """
883
 
 
884
 
    def _raise_invalid(self, numstring, context_branch):
885
 
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
886
 
                                         'No such line: %s' % numstring)
887
 
 
888
 
    def _as_revision_id(self, context_branch):
889
 
        path, numstring = self.spec.rsplit(':', 1)
890
 
        try:
891
 
            index = int(numstring) - 1
892
 
        except ValueError:
893
 
            self._raise_invalid(numstring, context_branch)
894
 
        tree, file_path = workingtree.WorkingTree.open_containing(path)
895
 
        with tree.lock_read():
896
 
            if not tree.has_filename(file_path):
897
 
                raise errors.InvalidRevisionSpec(self.user_spec,
898
 
                                                 context_branch, "File '%s' is not versioned." %
899
 
                                                 file_path)
900
 
            revision_ids = [r for (r, l) in tree.annotate_iter(file_path)]
901
 
        try:
902
 
            revision_id = revision_ids[index]
903
 
        except IndexError:
904
 
            self._raise_invalid(numstring, context_branch)
905
 
        if revision_id == revision.CURRENT_REVISION:
906
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
907
 
                                             'Line %s has not been committed.' % numstring)
908
 
        return revision_id
909
 
 
910
 
 
911
 
class RevisionSpec_mainline(RevisionIDSpec):
912
 
 
913
 
    help_txt = """Select mainline revision that merged the specified revision.
914
 
 
915
 
    Select the revision that merged the specified revision into mainline.
916
 
    """
917
 
 
918
 
    prefix = 'mainline:'
919
 
 
920
 
    def _as_revision_id(self, context_branch):
921
 
        revspec = RevisionSpec.from_string(self.spec)
922
 
        if revspec.get_branch() is None:
923
 
            spec_branch = context_branch
924
 
        else:
925
 
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
926
 
        revision_id = revspec.as_revision_id(spec_branch)
927
 
        graph = context_branch.repository.get_graph()
928
 
        result = graph.find_lefthand_merger(revision_id,
929
 
                                            context_branch.last_revision())
930
 
        if result is None:
931
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
932
 
        return result
 
896
            self._get_submit_location(context_branch))
933
897
 
934
898
 
935
899
# The order in which we want to DWIM a revision spec without any prefix.
936
900
# revno is always tried first and isn't listed here, this is used by
937
901
# RevisionSpec_dwim._match_on
938
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
939
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
940
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
941
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
 
902
dwim_revspecs = [
 
903
    RevisionSpec_tag, # Let's try for a tag
 
904
    RevisionSpec_revid, # Maybe it's a revid?
 
905
    RevisionSpec_date, # Perhaps a date?
 
906
    RevisionSpec_branch, # OK, last try, maybe it's a branch
 
907
    ]
 
908
 
942
909
 
943
910
revspec_registry = registry.Registry()
944
 
 
945
 
 
946
911
def _register_revspec(revspec):
947
912
    revspec_registry.register(revspec.prefix, revspec)
948
913
 
949
 
 
950
914
_register_revspec(RevisionSpec_revno)
951
915
_register_revspec(RevisionSpec_revid)
952
916
_register_revspec(RevisionSpec_last)
956
920
_register_revspec(RevisionSpec_ancestor)
957
921
_register_revspec(RevisionSpec_branch)
958
922
_register_revspec(RevisionSpec_submit)
959
 
_register_revspec(RevisionSpec_annotate)
960
 
_register_revspec(RevisionSpec_mainline)
 
923
 
 
924
# classes in this list should have a "prefix" attribute, against which
 
925
# string specs are matched
 
926
SPEC_TYPES = symbol_versioning.deprecated_list(
 
927
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])