/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-04-05 19:11:34 UTC
  • mto: (7490.7.16 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200405191134-0aebh8ikiwygxma5
Populate the .gitignore file.

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