/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: 2018-06-14 17:59:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7065.
  • Revision ID: jelmer@jelmer.uk-20180614175916-a2e2xh5k533guq1x
Move breezy.plugins.git to breezy.git.

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
 
17
19
 
18
20
from .lazy_import import lazy_import
19
21
lazy_import(globals(), """
23
25
from breezy import (
24
26
    branch as _mod_branch,
25
27
    cache_utf8,
 
28
    osutils,
26
29
    revision,
27
30
    workingtree,
28
31
    )
35
38
    registry,
36
39
    trace,
37
40
    )
38
 
 
39
 
 
40
 
class InvalidRevisionSpec(errors.BzrError):
41
 
 
42
 
    _fmt = ("Requested revision: '%(spec)s' does not exist in branch:"
43
 
            " %(branch_url)s%(extra)s")
44
 
 
45
 
    def __init__(self, spec, branch, extra=None):
46
 
        errors.BzrError.__init__(self, branch=branch, spec=spec)
47
 
        self.branch_url = getattr(branch, 'user_url', str(branch))
48
 
        if extra:
49
 
            self.extra = '\n' + str(extra)
50
 
        else:
51
 
            self.extra = ''
52
 
 
53
 
 
54
 
class InvalidRevisionSpec(errors.BzrError):
55
 
 
56
 
    _fmt = ("Requested revision: '%(spec)s' does not exist in branch:"
57
 
            " %(branch_url)s%(extra)s")
58
 
 
59
 
    def __init__(self, spec, branch, extra=None):
60
 
        errors.BzrError.__init__(self, branch=branch, spec=spec)
61
 
        self.branch_url = getattr(branch, 'user_url', str(branch))
62
 
        if extra:
63
 
            self.extra = '\n' + str(extra)
64
 
        else:
65
 
            self.extra = ''
 
41
from .sixish import (
 
42
    text_type,
 
43
    )
66
44
 
67
45
 
68
46
class RevisionInfo(object):
96
74
        if not self._has_revno and self.rev_id is not None:
97
75
            try:
98
76
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
99
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
77
            except errors.NoSuchRevision:
100
78
                self._revno = None
101
79
            self._has_revno = True
102
80
        return self._revno
115
93
        return 2
116
94
 
117
95
    def __getitem__(self, index):
118
 
        if index == 0:
119
 
            return self.revno
120
 
        if index == 1:
121
 
            return self.rev_id
 
96
        if index == 0: return self.revno
 
97
        if index == 1: return self.rev_id
122
98
        raise IndexError(index)
123
99
 
124
100
    def get(self):
164
140
    """
165
141
 
166
142
    prefix = None
167
 
    dwim_catchable_exceptions = (InvalidRevisionSpec,)
 
143
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
168
144
    """Exceptions that RevisionSpec_dwim._match_on will catch.
169
145
 
170
146
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
183
159
        """
184
160
        if spec is None:
185
161
            return RevisionSpec(None, _internal=True)
186
 
        if not isinstance(spec, str):
 
162
        if not isinstance(spec, (str, text_type)):
187
163
            raise TypeError("revision spec needs to be text")
188
164
        match = revspec_registry.get_prefix(spec)
189
165
        if match is not None:
224
200
            # special case - nothing supplied
225
201
            return info
226
202
        elif self.prefix:
227
 
            raise InvalidRevisionSpec(self.user_spec, branch)
 
203
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
228
204
        else:
229
 
            raise InvalidRevisionSpec(self.spec, branch)
 
205
            raise errors.InvalidRevisionSpec(self.spec, branch)
230
206
 
231
207
    def in_history(self, branch):
232
208
        return self._match_on_and_check(branch, revs=None)
279
255
    def __repr__(self):
280
256
        # this is mostly for helping with testing
281
257
        return '<%s %s>' % (self.__class__.__name__,
282
 
                            self.user_spec)
 
258
                              self.user_spec)
283
259
 
284
260
    def needs_branch(self):
285
261
        """Whether this revision spec needs a branch.
341
317
        # Well, I dunno what it is. Note that we don't try to keep track of the
342
318
        # first of last exception raised during the DWIM tries as none seems
343
319
        # really relevant.
344
 
        raise InvalidRevisionSpec(self.spec, branch)
 
320
        raise errors.InvalidRevisionSpec(self.spec, branch)
345
321
 
346
322
    @classmethod
347
323
    def append_possible_revspec(cls, revspec):
397
373
            branch_spec = None
398
374
        else:
399
375
            revno_spec = self.spec[:loc]
400
 
            branch_spec = self.spec[loc + 1:]
 
376
            branch_spec = self.spec[loc+1:]
401
377
 
402
378
        if revno_spec == '':
403
379
            if not branch_spec:
404
 
                raise InvalidRevisionSpec(
405
 
                    self.user_spec, branch,
406
 
                    'cannot have an empty revno and no branch')
 
380
                raise errors.InvalidRevisionSpec(self.user_spec,
 
381
                        branch, 'cannot have an empty revno and no branch')
407
382
            revno = None
408
383
        else:
409
384
            try:
414
389
                # but the from_string method is a little primitive
415
390
                # right now - RBC 20060928
416
391
                try:
417
 
                    match_revno = tuple((int(number)
418
 
                                         for number in revno_spec.split('.')))
 
392
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
419
393
                except ValueError as e:
420
 
                    raise InvalidRevisionSpec(self.user_spec, branch, e)
 
394
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
421
395
 
422
396
                dotted = True
423
397
 
428
402
        if dotted:
429
403
            try:
430
404
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
431
 
                                                                 _cache_reverse=True)
432
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
433
 
                raise InvalidRevisionSpec(self.user_spec, branch)
 
405
                    _cache_reverse=True)
 
406
            except errors.NoSuchRevision:
 
407
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
434
408
            else:
435
409
                # there is no traditional 'revno' for dotted-decimal revnos.
436
410
                # so for API compatibility we return None.
446
420
                    revno = last_revno + revno + 1
447
421
            try:
448
422
                revision_id = branch.get_rev_id(revno)
449
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
450
 
                raise InvalidRevisionSpec(self.user_spec, branch)
 
423
            except errors.NoSuchRevision:
 
424
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
451
425
        return branch, revno, revision_id
452
426
 
453
427
    def _as_revision_id(self, context_branch):
462
436
        if self.spec.find(':') == -1:
463
437
            return None
464
438
        else:
465
 
            return self.spec[self.spec.find(':') + 1:]
466
 
 
 
439
            return self.spec[self.spec.find(':')+1:]
467
440
 
468
441
# Old compatibility
469
442
RevisionSpec_int = RevisionSpec_revno
495
468
        # self.spec comes straight from parsing the command line arguments,
496
469
        # so we expect it to be a Unicode string. Switch it to the internal
497
470
        # representation.
498
 
        if isinstance(self.spec, str):
 
471
        if isinstance(self.spec, unicode):
499
472
            return cache_utf8.encode(self.spec)
500
473
        return self.spec
501
474
 
502
475
 
 
476
 
503
477
class RevisionSpec_last(RevisionSpec):
504
478
    """Selects the nth revision from the end."""
505
479
 
530
504
        try:
531
505
            offset = int(self.spec)
532
506
        except ValueError as e:
533
 
            raise InvalidRevisionSpec(self.user_spec, context_branch, e)
 
507
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
534
508
 
535
509
        if offset <= 0:
536
 
            raise InvalidRevisionSpec(
537
 
                self.user_spec, context_branch,
538
 
                'you must supply a positive value')
 
510
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
511
                                             'you must supply a positive value')
539
512
 
540
513
        revno = last_revno - offset + 1
541
514
        try:
542
515
            revision_id = context_branch.get_rev_id(revno)
543
 
        except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
544
 
            raise InvalidRevisionSpec(self.user_spec, context_branch)
 
516
        except errors.NoSuchRevision:
 
517
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
545
518
        return revno, revision_id
546
519
 
547
520
    def _as_revision_id(self, context_branch):
551
524
        return revision_id
552
525
 
553
526
 
 
527
 
554
528
class RevisionSpec_before(RevisionSpec):
555
529
    """Selects the parent of the revision specified."""
556
530
 
578
552
    def _match_on(self, branch, revs):
579
553
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
580
554
        if r.revno == 0:
581
 
            raise InvalidRevisionSpec(
582
 
                self.user_spec, branch,
583
 
                'cannot go before the null: revision')
 
555
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
556
                                         'cannot go before the null: revision')
584
557
        if r.revno is None:
585
558
            # We need to use the repository history here
586
559
            rev = branch.repository.get_revision(r.rev_id)
593
566
            revno = r.revno - 1
594
567
            try:
595
568
                revision_id = branch.get_rev_id(revno, revs)
596
 
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
597
 
                raise InvalidRevisionSpec(self.user_spec, branch)
 
569
            except errors.NoSuchRevision:
 
570
                raise errors.InvalidRevisionSpec(self.user_spec,
 
571
                                                 branch)
598
572
        return RevisionInfo(branch, revno, revision_id)
599
573
 
600
574
    def _as_revision_id(self, context_branch):
601
 
        base_revision_id = RevisionSpec.from_string(
602
 
            self.spec)._as_revision_id(context_branch)
 
575
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
603
576
        if base_revision_id == revision.NULL_REVISION:
604
 
            raise InvalidRevisionSpec(
605
 
                self.user_spec, context_branch,
606
 
                'cannot go before the null: revision')
 
577
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
578
                                         'cannot go before the null: revision')
607
579
        context_repo = context_branch.repository
608
 
        with context_repo.lock_read():
 
580
        context_repo.lock_read()
 
581
        try:
609
582
            parent_map = context_repo.get_parent_map([base_revision_id])
 
583
        finally:
 
584
            context_repo.unlock()
610
585
        if base_revision_id not in parent_map:
611
586
            # Ghost, or unknown revision id
612
 
            raise InvalidRevisionSpec(
613
 
                self.user_spec, context_branch, 'cannot find the matching revision')
 
587
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
588
                'cannot find the matching revision')
614
589
        parents = parent_map[base_revision_id]
615
590
        if len(parents) < 1:
616
 
            raise InvalidRevisionSpec(
617
 
                self.user_spec, context_branch, 'No parents for revision.')
 
591
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
592
                'No parents for revision.')
618
593
        return parents[0]
619
594
 
620
595
 
 
596
 
621
597
class RevisionSpec_tag(RevisionSpec):
622
598
    """Select a revision identified by tag name"""
623
599
 
632
608
    def _match_on(self, branch, revs):
633
609
        # Can raise tags not supported, NoSuchTag, etc
634
610
        return RevisionInfo.from_revision_id(branch,
635
 
                                             branch.tags.lookup_tag(self.spec))
 
611
            branch.tags.lookup_tag(self.spec))
636
612
 
637
613
    def _as_revision_id(self, context_branch):
638
614
        return context_branch.tags.lookup_tag(self.spec)
639
615
 
640
616
 
 
617
 
641
618
class _RevListToTimestamps(object):
642
619
    """This takes a list of revisions, and allows you to bisect by date"""
643
620
 
678
655
    """
679
656
    prefix = 'date:'
680
657
    _date_regex = lazy_regex.lazy_compile(
681
 
        r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
682
 
        r'(,|T)?\s*'
683
 
        r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
658
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
659
            r'(,|T)?\s*'
 
660
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
684
661
        )
685
662
 
686
663
    def _match_on(self, branch, revs):
693
670
        #  XXX: This doesn't actually work
694
671
        #  So the proper way of saying 'give me all entries for today' is:
695
672
        #      -r date:yesterday..date:today
696
 
        today = datetime.datetime.fromordinal(
697
 
            datetime.date.today().toordinal())
 
673
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
698
674
        if self.spec.lower() == 'yesterday':
699
675
            dt = today - datetime.timedelta(days=1)
700
676
        elif self.spec.lower() == 'today':
704
680
        else:
705
681
            m = self._date_regex.match(self.spec)
706
682
            if not m or (not m.group('date') and not m.group('time')):
707
 
                raise InvalidRevisionSpec(
708
 
                    self.user_spec, branch, 'invalid date')
 
683
                raise errors.InvalidRevisionSpec(self.user_spec,
 
684
                                                 branch, 'invalid date')
709
685
 
710
686
            try:
711
687
                if m.group('date'):
727
703
                else:
728
704
                    hour, minute, second = 0, 0, 0
729
705
            except ValueError:
730
 
                raise InvalidRevisionSpec(
731
 
                    self.user_spec, branch, 'invalid date')
 
706
                raise errors.InvalidRevisionSpec(self.user_spec,
 
707
                                                 branch, 'invalid date')
732
708
 
733
709
            dt = datetime.datetime(year=year, month=month, day=day,
734
 
                                   hour=hour, minute=minute, second=second)
 
710
                    hour=hour, minute=minute, second=second)
735
711
        with branch.lock_read():
736
712
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
737
713
        if rev == branch.revno():
738
 
            raise InvalidRevisionSpec(self.user_spec, branch)
 
714
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
739
715
        return RevisionInfo(branch, rev)
740
716
 
741
717
 
 
718
 
742
719
class RevisionSpec_ancestor(RevisionSpec):
743
720
    """Selects a common ancestor with a second branch."""
744
721
 
852
829
        return self.spec
853
830
 
854
831
 
 
832
 
855
833
class RevisionSpec_submit(RevisionSpec_ancestor):
856
834
    """Selects a common ancestor with a submit branch."""
857
835
 
882
860
        if submit_location is None:
883
861
            raise errors.NoSubmitBranch(branch)
884
862
        trace.note(gettext('Using {0} {1}').format(location_type,
885
 
                                                   submit_location))
 
863
                                                        submit_location))
886
864
        return submit_location
887
865
 
888
866
    def _match_on(self, branch, revs):
889
867
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
890
868
        return self._find_revision_info(branch,
891
 
                                        self._get_submit_location(branch))
 
869
            self._get_submit_location(branch))
892
870
 
893
871
    def _as_revision_id(self, context_branch):
894
872
        return self._find_revision_id(context_branch,
895
 
                                      self._get_submit_location(context_branch))
 
873
            self._get_submit_location(context_branch))
896
874
 
897
875
 
898
876
class RevisionSpec_annotate(RevisionIDSpec):
908
886
    """
909
887
 
910
888
    def _raise_invalid(self, numstring, context_branch):
911
 
        raise InvalidRevisionSpec(
912
 
            self.user_spec, context_branch,
 
889
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
913
890
            'No such line: %s' % numstring)
914
891
 
915
892
    def _as_revision_id(self, context_branch):
921
898
        tree, file_path = workingtree.WorkingTree.open_containing(path)
922
899
        with tree.lock_read():
923
900
            if not tree.has_filename(file_path):
924
 
                raise InvalidRevisionSpec(
925
 
                    self.user_spec, context_branch,
926
 
                    "File '%s' is not versioned." % file_path)
 
901
                raise errors.InvalidRevisionSpec(self.user_spec,
 
902
                    context_branch, "File '%s' is not versioned." %
 
903
                    file_path)
927
904
            revision_ids = [r for (r, l) in tree.annotate_iter(file_path)]
928
905
        try:
929
906
            revision_id = revision_ids[index]
930
907
        except IndexError:
931
908
            self._raise_invalid(numstring, context_branch)
932
909
        if revision_id == revision.CURRENT_REVISION:
933
 
            raise InvalidRevisionSpec(
934
 
                self.user_spec, context_branch,
 
910
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
935
911
                'Line %s has not been committed.' % numstring)
936
912
        return revision_id
937
913
 
956
932
        result = graph.find_lefthand_merger(revision_id,
957
933
                                            context_branch.last_revision())
958
934
        if result is None:
959
 
            raise InvalidRevisionSpec(self.user_spec, context_branch)
 
935
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
960
936
        return result
961
937
 
962
938
 
969
945
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
970
946
 
971
947
revspec_registry = registry.Registry()
972
 
 
973
 
 
974
948
def _register_revspec(revspec):
975
949
    revspec_registry.register(revspec.prefix, revspec)
976
950
 
977
 
 
978
951
_register_revspec(RevisionSpec_revno)
979
952
_register_revspec(RevisionSpec_revid)
980
953
_register_revspec(RevisionSpec_last)