/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 breezy/revisionspec.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-18 01:57:45 UTC
  • mto: This revision was merged to the branch mainline in revision 7493.
  • Revision ID: jelmer@jelmer.uk-20200218015745-q2ss9tsk74h4nh61
drop use of future.

Show diffs side-by-side

added added

removed removed

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