~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-15 11:53:48 UTC
  • mto: This revision was merged to the branch mainline in revision 6375.
  • Revision ID: jelmer@samba.org-20111215115348-murs91ipn8jbw6y0
Add tests for default_email behaviour.

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
18
from bzrlib.lazy_import import lazy_import
21
19
lazy_import(globals(), """
22
20
import bisect
23
21
import datetime
 
22
 
 
23
from bzrlib import (
 
24
    branch as _mod_branch,
 
25
    osutils,
 
26
    revision,
 
27
    symbol_versioning,
 
28
    workingtree,
 
29
    )
 
30
from bzrlib.i18n import gettext
24
31
""")
25
32
 
26
33
from bzrlib import (
27
34
    errors,
28
 
    osutils,
 
35
    lazy_regex,
29
36
    registry,
30
 
    revision,
31
 
    symbol_versioning,
32
37
    trace,
33
38
    )
34
39
 
35
40
 
36
 
_marker = []
37
 
 
38
 
 
39
41
class RevisionInfo(object):
40
42
    """The results of applying a revision specification to a branch."""
41
43
 
53
55
    or treat the result as a tuple.
54
56
    """
55
57
 
56
 
    def __init__(self, branch, revno, rev_id=_marker):
 
58
    def __init__(self, branch, revno=None, rev_id=None):
57
59
        self.branch = branch
58
 
        self.revno = revno
59
 
        if rev_id is _marker:
 
60
        self._has_revno = (revno is not None)
 
61
        self._revno = revno
 
62
        self.rev_id = rev_id
 
63
        if self.rev_id is None and self._revno is not None:
60
64
            # 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
 
65
            self.rev_id = branch.get_rev_id(self._revno)
 
66
 
 
67
    @property
 
68
    def revno(self):
 
69
        if not self._has_revno and self.rev_id is not None:
 
70
            try:
 
71
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
 
72
            except errors.NoSuchRevision:
 
73
                self._revno = None
 
74
            self._has_revno = True
 
75
        return self._revno
67
76
 
68
77
    def __nonzero__(self):
69
78
        # first the easy ones...
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, revs=symbol_versioning.DEPRECATED_PARAMETER):
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
        if symbol_versioning.deprecated_passed(revs):
 
117
            symbol_versioning.warn(
 
118
                'RevisionInfo.from_revision_id(revs) was deprecated in 2.5.',
 
119
                DeprecationWarning,
 
120
                stacklevel=2)
 
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
 
144
    # wants_revision_history has been deprecated in 2.5.
 
145
    wants_revision_history = False
140
146
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
141
147
    """Exceptions that RevisionSpec_dwim._match_on will catch.
142
148
 
166
172
                         spectype.__name__, spec)
167
173
            return spectype(spec, _internal=True)
168
174
        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
175
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
175
176
            # wait for _match_on to be called.
176
177
            return RevisionSpec_dwim(spec, _internal=True)
212
213
    def in_history(self, branch):
213
214
        if branch:
214
215
            if self.wants_revision_history:
215
 
                revs = branch.revision_history()
 
216
                symbol_versioning.warn(
 
217
                    "RevisionSpec.wants_revision_history was "
 
218
                    "deprecated in 2.5 (%s)." % self.__class__.__name__,
 
219
                    DeprecationWarning)
 
220
                branch.lock_read()
 
221
                try:
 
222
                    graph = branch.repository.get_graph()
 
223
                    revs = list(graph.iter_lefthand_ancestry(
 
224
                        branch.last_revision(), [revision.NULL_REVISION]))
 
225
                finally:
 
226
                    branch.unlock()
 
227
                revs.reverse()
216
228
            else:
217
229
                revs = None
218
230
        else:
298
310
    """
299
311
 
300
312
    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
 
313
 
 
314
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
315
 
 
316
    # The revspecs to try
 
317
    _possible_revspecs = []
304
318
 
305
319
    def _try_spectype(self, rstype, branch):
306
320
        rs = rstype(self.spec, _internal=True)
312
326
        """Run the lookup and see what we can get."""
313
327
 
314
328
        # 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:
 
329
        if self._revno_regex.match(self.spec) is not None:
319
330
            try:
320
331
                return self._try_spectype(RevisionSpec_revno, branch)
321
332
            except RevisionSpec_revno.dwim_catchable_exceptions:
322
333
                pass
323
334
 
324
335
        # Next see what has been registered
 
336
        for objgetter in self._possible_revspecs:
 
337
            rs_class = objgetter.get_obj()
 
338
            try:
 
339
                return self._try_spectype(rs_class, branch)
 
340
            except rs_class.dwim_catchable_exceptions:
 
341
                pass
 
342
 
 
343
        # Try the old (deprecated) dwim list:
325
344
        for rs_class in dwim_revspecs:
326
345
            try:
327
346
                return self._try_spectype(rs_class, branch)
333
352
        # really relevant.
334
353
        raise errors.InvalidRevisionSpec(self.spec, branch)
335
354
 
 
355
    @classmethod
 
356
    def append_possible_revspec(cls, revspec):
 
357
        """Append a possible DWIM revspec.
 
358
 
 
359
        :param revspec: Revision spec to try.
 
360
        """
 
361
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
 
362
 
 
363
    @classmethod
 
364
    def append_possible_lazy_revspec(cls, module_name, member_name):
 
365
        """Append a possible lazily loaded DWIM revspec.
 
366
 
 
367
        :param module_name: Name of the module with the revspec
 
368
        :param member_name: Name of the revspec within the module
 
369
        """
 
370
        cls._possible_revspecs.append(
 
371
            registry._LazyObjectGetter(module_name, member_name))
 
372
 
336
373
 
337
374
class RevisionSpec_revno(RevisionSpec):
338
375
    """Selects a revision using a number."""
356
393
                                   your history is very long.
357
394
    """
358
395
    prefix = 'revno:'
359
 
    wants_revision_history = False
360
396
 
361
397
    def _match_on(self, branch, revs):
362
398
        """Lookup a revision by revision number"""
363
 
        branch, revno, revision_id = self._lookup(branch, revs)
 
399
        branch, revno, revision_id = self._lookup(branch)
364
400
        return RevisionInfo(branch, revno, revision_id)
365
401
 
366
 
    def _lookup(self, branch, revs_or_none):
 
402
    def _lookup(self, branch):
367
403
        loc = self.spec.find(':')
368
404
        if loc == -1:
369
405
            revno_spec = self.spec
393
429
                dotted = True
394
430
 
395
431
        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
 
432
            # the user has overriden the branch to look in.
 
433
            branch = _mod_branch.Branch.open(branch_spec)
402
434
 
403
435
        if dotted:
404
436
            try:
408
440
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
409
441
            else:
410
442
                # there is no traditional 'revno' for dotted-decimal revnos.
411
 
                # so for  API compatability we return None.
 
443
                # so for API compatibility we return None.
412
444
                return branch, None, revision_id
413
445
        else:
414
446
            last_revno, last_revision_id = branch.last_revision_info()
420
452
                else:
421
453
                    revno = last_revno + revno + 1
422
454
            try:
423
 
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
455
                revision_id = branch.get_rev_id(revno)
424
456
            except errors.NoSuchRevision:
425
457
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
426
458
        return branch, revno, revision_id
427
459
 
428
460
    def _as_revision_id(self, context_branch):
429
461
        # We would have the revno here, but we don't really care
430
 
        branch, revno, revision_id = self._lookup(context_branch, None)
 
462
        branch, revno, revision_id = self._lookup(context_branch)
431
463
        return revision_id
432
464
 
433
465
    def needs_branch(self):
443
475
RevisionSpec_int = RevisionSpec_revno
444
476
 
445
477
 
446
 
 
447
 
class RevisionSpec_revid(RevisionSpec):
 
478
class RevisionIDSpec(RevisionSpec):
 
479
 
 
480
    def _match_on(self, branch, revs):
 
481
        revision_id = self.as_revision_id(branch)
 
482
        return RevisionInfo.from_revision_id(branch, revision_id)
 
483
 
 
484
 
 
485
class RevisionSpec_revid(RevisionIDSpec):
448
486
    """Selects a revision using the revision id."""
449
487
 
450
488
    help_txt = """Selects a revision using the revision id.
459
497
 
460
498
    prefix = 'revid:'
461
499
 
462
 
    def _match_on(self, branch, revs):
 
500
    def _as_revision_id(self, context_branch):
463
501
        # self.spec comes straight from parsing the command line arguments,
464
502
        # so we expect it to be a Unicode string. Switch it to the internal
465
503
        # 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
504
        return osutils.safe_revision_id(self.spec, warn=False)
471
505
 
472
506
 
487
521
    prefix = 'last:'
488
522
 
489
523
    def _match_on(self, branch, revs):
490
 
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
524
        revno, revision_id = self._revno_and_revision_id(branch)
491
525
        return RevisionInfo(branch, revno, revision_id)
492
526
 
493
 
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
527
    def _revno_and_revision_id(self, context_branch):
494
528
        last_revno, last_revision_id = context_branch.last_revision_info()
495
529
 
496
530
        if self.spec == '':
509
543
 
510
544
        revno = last_revno - offset + 1
511
545
        try:
512
 
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
 
546
            revision_id = context_branch.get_rev_id(revno)
513
547
        except errors.NoSuchRevision:
514
548
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
515
549
        return revno, revision_id
517
551
    def _as_revision_id(self, context_branch):
518
552
        # We compute the revno as part of the process, but we don't really care
519
553
        # about it.
520
 
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
554
        revno, revision_id = self._revno_and_revision_id(context_branch)
521
555
        return revision_id
522
556
 
523
557
 
555
589
            # We need to use the repository history here
556
590
            rev = branch.repository.get_revision(r.rev_id)
557
591
            if not rev.parent_ids:
558
 
                revno = 0
559
592
                revision_id = revision.NULL_REVISION
560
593
            else:
561
594
                revision_id = rev.parent_ids[0]
562
 
                try:
563
 
                    revno = revs.index(revision_id) + 1
564
 
                except ValueError:
565
 
                    revno = None
 
595
            revno = None
566
596
        else:
567
597
            revno = r.revno - 1
568
598
            try:
573
603
        return RevisionInfo(branch, revno, revision_id)
574
604
 
575
605
    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)
 
606
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
578
607
        if base_revision_id == revision.NULL_REVISION:
579
608
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
580
609
                                         'cannot go before the null: revision')
610
639
    def _match_on(self, branch, revs):
611
640
        # Can raise tags not supported, NoSuchTag, etc
612
641
        return RevisionInfo.from_revision_id(branch,
613
 
            branch.tags.lookup_tag(self.spec),
614
 
            revs)
 
642
            branch.tags.lookup_tag(self.spec))
615
643
 
616
644
    def _as_revision_id(self, context_branch):
617
645
        return context_branch.tags.lookup_tag(self.spec)
621
649
class _RevListToTimestamps(object):
622
650
    """This takes a list of revisions, and allows you to bisect by date"""
623
651
 
624
 
    __slots__ = ['revs', 'branch']
 
652
    __slots__ = ['branch']
625
653
 
626
 
    def __init__(self, revs, branch):
627
 
        self.revs = revs
 
654
    def __init__(self, branch):
628
655
        self.branch = branch
629
656
 
630
657
    def __getitem__(self, index):
631
658
        """Get the date of the index'd item"""
632
 
        r = self.branch.repository.get_revision(self.revs[index])
 
659
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
633
660
        # TODO: Handle timezone.
634
661
        return datetime.datetime.fromtimestamp(r.timestamp)
635
662
 
636
663
    def __len__(self):
637
 
        return len(self.revs)
 
664
        return self.branch.revno()
638
665
 
639
666
 
640
667
class RevisionSpec_date(RevisionSpec):
658
685
                                   August 14th, 2006 at 5:10pm.
659
686
    """
660
687
    prefix = 'date:'
661
 
    _date_re = re.compile(
 
688
    _date_regex = lazy_regex.lazy_compile(
662
689
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
663
690
            r'(,|T)?\s*'
664
691
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
682
709
        elif self.spec.lower() == 'tomorrow':
683
710
            dt = today + datetime.timedelta(days=1)
684
711
        else:
685
 
            m = self._date_re.match(self.spec)
 
712
            m = self._date_regex.match(self.spec)
686
713
            if not m or (not m.group('date') and not m.group('time')):
687
714
                raise errors.InvalidRevisionSpec(self.user_spec,
688
715
                                                 branch, 'invalid date')
714
741
                    hour=hour, minute=minute, second=second)
715
742
        branch.lock_read()
716
743
        try:
717
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
744
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
718
745
        finally:
719
746
            branch.unlock()
720
 
        if rev == len(revs):
 
747
        if rev == branch.revno():
721
748
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
722
 
        else:
723
 
            return RevisionInfo(branch, rev + 1)
 
749
        return RevisionInfo(branch, rev)
724
750
 
725
751
 
726
752
 
757
783
    def _find_revision_info(branch, other_location):
758
784
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
759
785
                                                              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)
 
786
        return RevisionInfo(branch, None, revision_id)
765
787
 
766
788
    @staticmethod
767
789
    def _find_revision_id(branch, other_location):
813
835
        revision_b = other_branch.last_revision()
814
836
        if revision_b in (None, revision.NULL_REVISION):
815
837
            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)
 
838
        if branch is None:
 
839
            branch = other_branch
 
840
        else:
 
841
            try:
 
842
                # pull in the remote revisions so we can diff
 
843
                branch.fetch(other_branch, revision_b)
 
844
            except errors.ReadOnlyError:
 
845
                branch = other_branch
 
846
        return RevisionInfo(branch, None, revision_b)
823
847
 
824
848
    def _as_revision_id(self, context_branch):
825
849
        from bzrlib.branch import Branch
840
864
            raise errors.NoCommits(other_branch)
841
865
        return other_branch.repository.revision_tree(last_revision)
842
866
 
 
867
    def needs_branch(self):
 
868
        return False
 
869
 
 
870
    def get_branch(self):
 
871
        return self.spec
 
872
 
843
873
 
844
874
 
845
875
class RevisionSpec_submit(RevisionSpec_ancestor):
871
901
            location_type = 'parent branch'
872
902
        if submit_location is None:
873
903
            raise errors.NoSubmitBranch(branch)
874
 
        trace.note('Using %s %s', location_type, submit_location)
 
904
        trace.note(gettext('Using {0} {1}').format(location_type,
 
905
                                                        submit_location))
875
906
        return submit_location
876
907
 
877
908
    def _match_on(self, branch, revs):
884
915
            self._get_submit_location(context_branch))
885
916
 
886
917
 
 
918
class RevisionSpec_annotate(RevisionIDSpec):
 
919
 
 
920
    prefix = 'annotate:'
 
921
 
 
922
    help_txt = """Select the revision that last modified the specified line.
 
923
 
 
924
    Select the revision that last modified the specified line.  Line is
 
925
    specified as path:number.  Path is a relative path to the file.  Numbers
 
926
    start at 1, and are relative to the current version, not the last-
 
927
    committed version of the file.
 
928
    """
 
929
 
 
930
    def _raise_invalid(self, numstring, context_branch):
 
931
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
932
            'No such line: %s' % numstring)
 
933
 
 
934
    def _as_revision_id(self, context_branch):
 
935
        path, numstring = self.spec.rsplit(':', 1)
 
936
        try:
 
937
            index = int(numstring) - 1
 
938
        except ValueError:
 
939
            self._raise_invalid(numstring, context_branch)
 
940
        tree, file_path = workingtree.WorkingTree.open_containing(path)
 
941
        tree.lock_read()
 
942
        try:
 
943
            file_id = tree.path2id(file_path)
 
944
            if file_id is None:
 
945
                raise errors.InvalidRevisionSpec(self.user_spec,
 
946
                    context_branch, "File '%s' is not versioned." %
 
947
                    file_path)
 
948
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
 
949
        finally:
 
950
            tree.unlock()
 
951
        try:
 
952
            revision_id = revision_ids[index]
 
953
        except IndexError:
 
954
            self._raise_invalid(numstring, context_branch)
 
955
        if revision_id == revision.CURRENT_REVISION:
 
956
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
957
                'Line %s has not been committed.' % numstring)
 
958
        return revision_id
 
959
 
 
960
 
 
961
class RevisionSpec_mainline(RevisionIDSpec):
 
962
 
 
963
    help_txt = """Select mainline revision that merged the specified revision.
 
964
 
 
965
    Select the revision that merged the specified revision into mainline.
 
966
    """
 
967
 
 
968
    prefix = 'mainline:'
 
969
 
 
970
    def _as_revision_id(self, context_branch):
 
971
        revspec = RevisionSpec.from_string(self.spec)
 
972
        if revspec.get_branch() is None:
 
973
            spec_branch = context_branch
 
974
        else:
 
975
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
 
976
        revision_id = revspec.as_revision_id(spec_branch)
 
977
        graph = context_branch.repository.get_graph()
 
978
        result = graph.find_lefthand_merger(revision_id,
 
979
                                            context_branch.last_revision())
 
980
        if result is None:
 
981
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
982
        return result
 
983
 
 
984
 
887
985
# The order in which we want to DWIM a revision spec without any prefix.
888
986
# revno is always tried first and isn't listed here, this is used by
889
987
# 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
 
    ]
 
988
dwim_revspecs = symbol_versioning.deprecated_list(
 
989
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])
896
990
 
 
991
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
 
992
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
 
993
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
 
994
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
897
995
 
898
996
revspec_registry = registry.Registry()
899
997
def _register_revspec(revspec):
908
1006
_register_revspec(RevisionSpec_ancestor)
909
1007
_register_revspec(RevisionSpec_branch)
910
1008
_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", [])
 
1009
_register_revspec(RevisionSpec_annotate)
 
1010
_register_revspec(RevisionSpec_mainline)