/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: 2017-07-23 22:06:41 UTC
  • mfrom: (6738 trunk)
  • mto: This revision was merged to the branch mainline in revision 6739.
  • Revision ID: jelmer@jelmer.uk-20170723220641-69eczax9bmv8d6kk
Merge trunk, address review comments.

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'):
725
701
                    else:
726
702
                        second = 0
727
703
                else:
728
 
                    hour, minute, second = 0, 0, 0
 
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)
735
 
        with branch.lock_read():
 
710
                    hour=hour, minute=minute, second=second)
 
711
        branch.lock_read()
 
712
        try:
736
713
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
 
714
        finally:
 
715
            branch.unlock()
737
716
        if rev == branch.revno():
738
 
            raise InvalidRevisionSpec(self.user_spec, branch)
 
717
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
739
718
        return RevisionInfo(branch, rev)
740
719
 
741
720
 
 
721
 
742
722
class RevisionSpec_ancestor(RevisionSpec):
743
723
    """Selects a common ancestor with a second branch."""
744
724
 
778
758
    def _find_revision_id(branch, other_location):
779
759
        from .branch import Branch
780
760
 
781
 
        with branch.lock_read():
 
761
        branch.lock_read()
 
762
        try:
782
763
            revision_a = revision.ensure_null(branch.last_revision())
783
764
            if revision_a == revision.NULL_REVISION:
784
765
                raise errors.NoCommits(branch)
785
766
            if other_location == '':
786
767
                other_location = branch.get_parent()
787
768
            other_branch = Branch.open(other_location)
788
 
            with other_branch.lock_read():
 
769
            other_branch.lock_read()
 
770
            try:
789
771
                revision_b = revision.ensure_null(other_branch.last_revision())
790
772
                if revision_b == revision.NULL_REVISION:
791
773
                    raise errors.NoCommits(other_branch)
792
774
                graph = branch.repository.get_graph(other_branch.repository)
793
775
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
776
            finally:
 
777
                other_branch.unlock()
794
778
            if rev_id == revision.NULL_REVISION:
795
779
                raise errors.NoCommonAncestor(revision_a, revision_b)
796
780
            return rev_id
 
781
        finally:
 
782
            branch.unlock()
 
783
 
 
784
 
797
785
 
798
786
 
799
787
class RevisionSpec_branch(RevisionSpec):
852
840
        return self.spec
853
841
 
854
842
 
 
843
 
855
844
class RevisionSpec_submit(RevisionSpec_ancestor):
856
845
    """Selects a common ancestor with a submit branch."""
857
846
 
882
871
        if submit_location is None:
883
872
            raise errors.NoSubmitBranch(branch)
884
873
        trace.note(gettext('Using {0} {1}').format(location_type,
885
 
                                                   submit_location))
 
874
                                                        submit_location))
886
875
        return submit_location
887
876
 
888
877
    def _match_on(self, branch, revs):
889
878
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
890
879
        return self._find_revision_info(branch,
891
 
                                        self._get_submit_location(branch))
 
880
            self._get_submit_location(branch))
892
881
 
893
882
    def _as_revision_id(self, context_branch):
894
883
        return self._find_revision_id(context_branch,
895
 
                                      self._get_submit_location(context_branch))
 
884
            self._get_submit_location(context_branch))
896
885
 
897
886
 
898
887
class RevisionSpec_annotate(RevisionIDSpec):
908
897
    """
909
898
 
910
899
    def _raise_invalid(self, numstring, context_branch):
911
 
        raise InvalidRevisionSpec(
912
 
            self.user_spec, context_branch,
 
900
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
913
901
            'No such line: %s' % numstring)
914
902
 
915
903
    def _as_revision_id(self, context_branch):
919
907
        except ValueError:
920
908
            self._raise_invalid(numstring, context_branch)
921
909
        tree, file_path = workingtree.WorkingTree.open_containing(path)
922
 
        with tree.lock_read():
923
 
            if not tree.has_filename(file_path):
924
 
                raise InvalidRevisionSpec(
925
 
                    self.user_spec, context_branch,
926
 
                    "File '%s' is not versioned." % file_path)
927
 
            revision_ids = [r for (r, l) in tree.annotate_iter(file_path)]
 
910
        tree.lock_read()
 
911
        try:
 
912
            file_id = tree.path2id(file_path)
 
913
            if file_id is None:
 
914
                raise errors.InvalidRevisionSpec(self.user_spec,
 
915
                    context_branch, "File '%s' is not versioned." %
 
916
                    file_path)
 
917
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
 
918
        finally:
 
919
            tree.unlock()
928
920
        try:
929
921
            revision_id = revision_ids[index]
930
922
        except IndexError:
931
923
            self._raise_invalid(numstring, context_branch)
932
924
        if revision_id == revision.CURRENT_REVISION:
933
 
            raise InvalidRevisionSpec(
934
 
                self.user_spec, context_branch,
 
925
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
935
926
                'Line %s has not been committed.' % numstring)
936
927
        return revision_id
937
928
 
956
947
        result = graph.find_lefthand_merger(revision_id,
957
948
                                            context_branch.last_revision())
958
949
        if result is None:
959
 
            raise InvalidRevisionSpec(self.user_spec, context_branch)
 
950
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
960
951
        return result
961
952
 
962
953
 
969
960
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
970
961
 
971
962
revspec_registry = registry.Registry()
972
 
 
973
 
 
974
963
def _register_revspec(revspec):
975
964
    revspec_registry.register(revspec.prefix, revspec)
976
965
 
977
 
 
978
966
_register_revspec(RevisionSpec_revno)
979
967
_register_revspec(RevisionSpec_revid)
980
968
_register_revspec(RevisionSpec_last)