~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Vincent Ladeuil
  • Date: 2010-12-07 10:16:53 UTC
  • mto: (5575.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 5576.
  • Revision ID: v.ladeuil+lp@free.fr-20101207101653-20iiufih26buvmy3
Use assertLength as it provides a better ouput to debug tests.

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
 
 
18
import re
19
19
 
20
20
from bzrlib.lazy_import import lazy_import
21
21
lazy_import(globals(), """
22
22
import bisect
23
23
import datetime
 
24
""")
24
25
 
25
26
from bzrlib import (
26
27
    branch as _mod_branch,
 
28
    errors,
27
29
    osutils,
 
30
    registry,
28
31
    revision,
29
32
    symbol_versioning,
 
33
    trace,
30
34
    workingtree,
31
35
    )
32
 
from bzrlib.i18n import gettext
33
 
""")
34
 
 
35
 
from bzrlib import (
36
 
    errors,
37
 
    lazy_regex,
38
 
    registry,
39
 
    trace,
40
 
    )
 
36
 
 
37
 
 
38
_marker = []
41
39
 
42
40
 
43
41
class RevisionInfo(object):
57
55
    or treat the result as a tuple.
58
56
    """
59
57
 
60
 
    def __init__(self, branch, revno=None, rev_id=None):
 
58
    def __init__(self, branch, revno, rev_id=_marker):
61
59
        self.branch = branch
62
 
        self._has_revno = (revno is not None)
63
 
        self._revno = revno
64
 
        self.rev_id = rev_id
65
 
        if self.rev_id is None and self._revno is not None:
 
60
        self.revno = revno
 
61
        if rev_id is _marker:
66
62
            # allow caller to be lazy
67
 
            self.rev_id = branch.get_rev_id(self._revno)
68
 
 
69
 
    @property
70
 
    def revno(self):
71
 
        if not self._has_revno and self.rev_id is not None:
72
 
            try:
73
 
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
74
 
            except errors.NoSuchRevision:
75
 
                self._revno = None
76
 
            self._has_revno = True
77
 
        return self._revno
 
63
            if self.revno is None:
 
64
                self.rev_id = None
 
65
            else:
 
66
                self.rev_id = branch.get_rev_id(self.revno)
 
67
        else:
 
68
            self.rev_id = rev_id
78
69
 
79
70
    def __nonzero__(self):
 
71
        # first the easy ones...
80
72
        if self.rev_id is None:
81
73
            return False
 
74
        if self.revno is not None:
 
75
            return True
82
76
        # TODO: otherwise, it should depend on how I was built -
83
77
        # if it's in_history(branch), then check revision_history(),
84
78
        # if it's in_store(branch), do the check below
107
101
            self.revno, self.rev_id, self.branch)
108
102
 
109
103
    @staticmethod
110
 
    def from_revision_id(branch, revision_id, revs=symbol_versioning.DEPRECATED_PARAMETER):
 
104
    def from_revision_id(branch, revision_id, revs):
111
105
        """Construct a RevisionInfo given just the id.
112
106
 
113
107
        Use this if you don't know or care what the revno is.
114
108
        """
115
 
        if symbol_versioning.deprecated_passed(revs):
116
 
            symbol_versioning.warn(
117
 
                'RevisionInfo.from_revision_id(revs) was deprecated in 2.5.',
118
 
                DeprecationWarning,
119
 
                stacklevel=2)
120
 
        return RevisionInfo(branch, revno=None, rev_id=revision_id)
 
109
        if revision_id == revision.NULL_REVISION:
 
110
            return RevisionInfo(branch, 0, revision_id)
 
111
        try:
 
112
            revno = revs.index(revision_id) + 1
 
113
        except ValueError:
 
114
            revno = None
 
115
        return RevisionInfo(branch, revno, revision_id)
 
116
 
 
117
 
 
118
_revno_regex = None
121
119
 
122
120
 
123
121
class RevisionSpec(object):
140
138
    """
141
139
 
142
140
    prefix = None
143
 
    # wants_revision_history has been deprecated in 2.5.
144
 
    wants_revision_history = False
 
141
    wants_revision_history = True
145
142
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
146
143
    """Exceptions that RevisionSpec_dwim._match_on will catch.
147
144
 
171
168
                         spectype.__name__, spec)
172
169
            return spectype(spec, _internal=True)
173
170
        else:
 
171
            for spectype in SPEC_TYPES:
 
172
                if spec.startswith(spectype.prefix):
 
173
                    trace.mutter('Returning RevisionSpec %s for %s',
 
174
                                 spectype.__name__, spec)
 
175
                    return spectype(spec, _internal=True)
174
176
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
175
177
            # wait for _match_on to be called.
176
178
            return RevisionSpec_dwim(spec, _internal=True)
212
214
    def in_history(self, branch):
213
215
        if branch:
214
216
            if self.wants_revision_history:
215
 
                symbol_versioning.warn(
216
 
                    "RevisionSpec.wants_revision_history was "
217
 
                    "deprecated in 2.5 (%s)." % self.__class__.__name__,
218
 
                    DeprecationWarning)
219
 
                branch.lock_read()
220
 
                try:
221
 
                    graph = branch.repository.get_graph()
222
 
                    revs = list(graph.iter_lefthand_ancestry(
223
 
                        branch.last_revision(), [revision.NULL_REVISION]))
224
 
                finally:
225
 
                    branch.unlock()
226
 
                revs.reverse()
 
217
                revs = branch.revision_history()
227
218
            else:
228
219
                revs = None
229
220
        else:
309
300
    """
310
301
 
311
302
    help_txt = None
312
 
 
313
 
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
314
 
 
315
 
    # The revspecs to try
316
 
    _possible_revspecs = []
 
303
    # We don't need to build the revision history ourself, that's delegated to
 
304
    # each revspec we try.
 
305
    wants_revision_history = False
317
306
 
318
307
    def _try_spectype(self, rstype, branch):
319
308
        rs = rstype(self.spec, _internal=True)
325
314
        """Run the lookup and see what we can get."""
326
315
 
327
316
        # First, see if it's a revno
328
 
        if self._revno_regex.match(self.spec) is not None:
 
317
        global _revno_regex
 
318
        if _revno_regex is None:
 
319
            _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
320
        if _revno_regex.match(self.spec) is not None:
329
321
            try:
330
322
                return self._try_spectype(RevisionSpec_revno, branch)
331
323
            except RevisionSpec_revno.dwim_catchable_exceptions:
332
324
                pass
333
325
 
334
326
        # Next see what has been registered
335
 
        for objgetter in self._possible_revspecs:
336
 
            rs_class = objgetter.get_obj()
337
 
            try:
338
 
                return self._try_spectype(rs_class, branch)
339
 
            except rs_class.dwim_catchable_exceptions:
340
 
                pass
341
 
 
342
 
        # Try the old (deprecated) dwim list:
343
327
        for rs_class in dwim_revspecs:
344
328
            try:
345
329
                return self._try_spectype(rs_class, branch)
351
335
        # really relevant.
352
336
        raise errors.InvalidRevisionSpec(self.spec, branch)
353
337
 
354
 
    @classmethod
355
 
    def append_possible_revspec(cls, revspec):
356
 
        """Append a possible DWIM revspec.
357
 
 
358
 
        :param revspec: Revision spec to try.
359
 
        """
360
 
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
361
 
 
362
 
    @classmethod
363
 
    def append_possible_lazy_revspec(cls, module_name, member_name):
364
 
        """Append a possible lazily loaded DWIM revspec.
365
 
 
366
 
        :param module_name: Name of the module with the revspec
367
 
        :param member_name: Name of the revspec within the module
368
 
        """
369
 
        cls._possible_revspecs.append(
370
 
            registry._LazyObjectGetter(module_name, member_name))
371
 
 
372
338
 
373
339
class RevisionSpec_revno(RevisionSpec):
374
340
    """Selects a revision using a number."""
392
358
                                   your history is very long.
393
359
    """
394
360
    prefix = 'revno:'
 
361
    wants_revision_history = False
395
362
 
396
363
    def _match_on(self, branch, revs):
397
364
        """Lookup a revision by revision number"""
398
 
        branch, revno, revision_id = self._lookup(branch)
 
365
        branch, revno, revision_id = self._lookup(branch, revs)
399
366
        return RevisionInfo(branch, revno, revision_id)
400
367
 
401
 
    def _lookup(self, branch):
 
368
    def _lookup(self, branch, revs_or_none):
402
369
        loc = self.spec.find(':')
403
370
        if loc == -1:
404
371
            revno_spec = self.spec
428
395
                dotted = True
429
396
 
430
397
        if branch_spec:
431
 
            # the user has overriden the branch to look in.
432
 
            branch = _mod_branch.Branch.open(branch_spec)
 
398
            # the user has override the branch to look in.
 
399
            # we need to refresh the revision_history map and
 
400
            # the branch object.
 
401
            from bzrlib.branch import Branch
 
402
            branch = Branch.open(branch_spec)
 
403
            revs_or_none = None
433
404
 
434
405
        if dotted:
435
406
            try:
439
410
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
440
411
            else:
441
412
                # there is no traditional 'revno' for dotted-decimal revnos.
442
 
                # so for API compatibility we return None.
 
413
                # so for  API compatability we return None.
443
414
                return branch, None, revision_id
444
415
        else:
445
416
            last_revno, last_revision_id = branch.last_revision_info()
451
422
                else:
452
423
                    revno = last_revno + revno + 1
453
424
            try:
454
 
                revision_id = branch.get_rev_id(revno)
 
425
                revision_id = branch.get_rev_id(revno, revs_or_none)
455
426
            except errors.NoSuchRevision:
456
427
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
457
428
        return branch, revno, revision_id
458
429
 
459
430
    def _as_revision_id(self, context_branch):
460
431
        # We would have the revno here, but we don't really care
461
 
        branch, revno, revision_id = self._lookup(context_branch)
 
432
        branch, revno, revision_id = self._lookup(context_branch, None)
462
433
        return revision_id
463
434
 
464
435
    def needs_branch(self):
474
445
RevisionSpec_int = RevisionSpec_revno
475
446
 
476
447
 
 
448
 
477
449
class RevisionIDSpec(RevisionSpec):
478
450
 
479
451
    def _match_on(self, branch, revs):
480
452
        revision_id = self.as_revision_id(branch)
481
 
        return RevisionInfo.from_revision_id(branch, revision_id)
 
453
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
482
454
 
483
455
 
484
456
class RevisionSpec_revid(RevisionIDSpec):
520
492
    prefix = 'last:'
521
493
 
522
494
    def _match_on(self, branch, revs):
523
 
        revno, revision_id = self._revno_and_revision_id(branch)
 
495
        revno, revision_id = self._revno_and_revision_id(branch, revs)
524
496
        return RevisionInfo(branch, revno, revision_id)
525
497
 
526
 
    def _revno_and_revision_id(self, context_branch):
 
498
    def _revno_and_revision_id(self, context_branch, revs_or_none):
527
499
        last_revno, last_revision_id = context_branch.last_revision_info()
528
500
 
529
501
        if self.spec == '':
542
514
 
543
515
        revno = last_revno - offset + 1
544
516
        try:
545
 
            revision_id = context_branch.get_rev_id(revno)
 
517
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
546
518
        except errors.NoSuchRevision:
547
519
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
548
520
        return revno, revision_id
550
522
    def _as_revision_id(self, context_branch):
551
523
        # We compute the revno as part of the process, but we don't really care
552
524
        # about it.
553
 
        revno, revision_id = self._revno_and_revision_id(context_branch)
 
525
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
554
526
        return revision_id
555
527
 
556
528
 
588
560
            # We need to use the repository history here
589
561
            rev = branch.repository.get_revision(r.rev_id)
590
562
            if not rev.parent_ids:
 
563
                revno = 0
591
564
                revision_id = revision.NULL_REVISION
592
565
            else:
593
566
                revision_id = rev.parent_ids[0]
594
 
            revno = None
 
567
                try:
 
568
                    revno = revs.index(revision_id) + 1
 
569
                except ValueError:
 
570
                    revno = None
595
571
        else:
596
572
            revno = r.revno - 1
597
573
            try:
602
578
        return RevisionInfo(branch, revno, revision_id)
603
579
 
604
580
    def _as_revision_id(self, context_branch):
605
 
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
 
581
        base_revspec = RevisionSpec.from_string(self.spec)
 
582
        base_revision_id = base_revspec.as_revision_id(context_branch)
606
583
        if base_revision_id == revision.NULL_REVISION:
607
584
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
608
585
                                         'cannot go before the null: revision')
638
615
    def _match_on(self, branch, revs):
639
616
        # Can raise tags not supported, NoSuchTag, etc
640
617
        return RevisionInfo.from_revision_id(branch,
641
 
            branch.tags.lookup_tag(self.spec))
 
618
            branch.tags.lookup_tag(self.spec),
 
619
            revs)
642
620
 
643
621
    def _as_revision_id(self, context_branch):
644
622
        return context_branch.tags.lookup_tag(self.spec)
648
626
class _RevListToTimestamps(object):
649
627
    """This takes a list of revisions, and allows you to bisect by date"""
650
628
 
651
 
    __slots__ = ['branch']
 
629
    __slots__ = ['revs', 'branch']
652
630
 
653
 
    def __init__(self, branch):
 
631
    def __init__(self, revs, branch):
 
632
        self.revs = revs
654
633
        self.branch = branch
655
634
 
656
635
    def __getitem__(self, index):
657
636
        """Get the date of the index'd item"""
658
 
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
 
637
        r = self.branch.repository.get_revision(self.revs[index])
659
638
        # TODO: Handle timezone.
660
639
        return datetime.datetime.fromtimestamp(r.timestamp)
661
640
 
662
641
    def __len__(self):
663
 
        return self.branch.revno()
 
642
        return len(self.revs)
664
643
 
665
644
 
666
645
class RevisionSpec_date(RevisionSpec):
684
663
                                   August 14th, 2006 at 5:10pm.
685
664
    """
686
665
    prefix = 'date:'
687
 
    _date_regex = lazy_regex.lazy_compile(
 
666
    _date_re = re.compile(
688
667
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
689
668
            r'(,|T)?\s*'
690
669
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
708
687
        elif self.spec.lower() == 'tomorrow':
709
688
            dt = today + datetime.timedelta(days=1)
710
689
        else:
711
 
            m = self._date_regex.match(self.spec)
 
690
            m = self._date_re.match(self.spec)
712
691
            if not m or (not m.group('date') and not m.group('time')):
713
692
                raise errors.InvalidRevisionSpec(self.user_spec,
714
693
                                                 branch, 'invalid date')
740
719
                    hour=hour, minute=minute, second=second)
741
720
        branch.lock_read()
742
721
        try:
743
 
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
 
722
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
744
723
        finally:
745
724
            branch.unlock()
746
 
        if rev == branch.revno():
 
725
        if rev == len(revs):
747
726
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
748
 
        return RevisionInfo(branch, rev)
 
727
        else:
 
728
            return RevisionInfo(branch, rev + 1)
749
729
 
750
730
 
751
731
 
782
762
    def _find_revision_info(branch, other_location):
783
763
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
784
764
                                                              other_location)
785
 
        return RevisionInfo(branch, None, revision_id)
 
765
        try:
 
766
            revno = branch.revision_id_to_revno(revision_id)
 
767
        except errors.NoSuchRevision:
 
768
            revno = None
 
769
        return RevisionInfo(branch, revno, revision_id)
786
770
 
787
771
    @staticmethod
788
772
    def _find_revision_id(branch, other_location):
842
826
                branch.fetch(other_branch, revision_b)
843
827
            except errors.ReadOnlyError:
844
828
                branch = other_branch
845
 
        return RevisionInfo(branch, None, revision_b)
 
829
        try:
 
830
            revno = branch.revision_id_to_revno(revision_b)
 
831
        except errors.NoSuchRevision:
 
832
            revno = None
 
833
        return RevisionInfo(branch, revno, revision_b)
846
834
 
847
835
    def _as_revision_id(self, context_branch):
848
836
        from bzrlib.branch import Branch
900
888
            location_type = 'parent branch'
901
889
        if submit_location is None:
902
890
            raise errors.NoSubmitBranch(branch)
903
 
        trace.note(gettext('Using {0} {1}').format(location_type,
904
 
                                                        submit_location))
 
891
        trace.note('Using %s %s', location_type, submit_location)
905
892
        return submit_location
906
893
 
907
894
    def _match_on(self, branch, revs):
984
971
# The order in which we want to DWIM a revision spec without any prefix.
985
972
# revno is always tried first and isn't listed here, this is used by
986
973
# RevisionSpec_dwim._match_on
987
 
dwim_revspecs = symbol_versioning.deprecated_list(
988
 
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])
 
974
dwim_revspecs = [
 
975
    RevisionSpec_tag, # Let's try for a tag
 
976
    RevisionSpec_revid, # Maybe it's a revid?
 
977
    RevisionSpec_date, # Perhaps a date?
 
978
    RevisionSpec_branch, # OK, last try, maybe it's a branch
 
979
    ]
989
980
 
990
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
991
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
992
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
993
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
994
981
 
995
982
revspec_registry = registry.Registry()
996
983
def _register_revspec(revspec):
1007
994
_register_revspec(RevisionSpec_submit)
1008
995
_register_revspec(RevisionSpec_annotate)
1009
996
_register_revspec(RevisionSpec_mainline)
 
997
 
 
998
# classes in this list should have a "prefix" attribute, against which
 
999
# string specs are matched
 
1000
SPEC_TYPES = symbol_versioning.deprecated_list(
 
1001
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])