~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Pool
  • Date: 2008-05-08 04:12:06 UTC
  • mto: This revision was merged to the branch mainline in revision 3415.
  • Revision ID: mbp@sourcefrog.net-20080508041206-tkrr8ucmcyrlzkum
Some review cleanups for assertion removal

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
 
18
 
import re
19
 
 
20
 
from bzrlib.lazy_import import lazy_import
21
 
lazy_import(globals(), """
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
22
18
import bisect
23
19
import datetime
24
 
""")
 
20
import re
25
21
 
26
22
from bzrlib import (
27
23
    errors,
28
24
    osutils,
29
 
    registry,
30
25
    revision,
31
26
    symbol_versioning,
32
27
    trace,
 
28
    tsort,
33
29
    )
34
30
 
35
31
 
113
109
        return RevisionInfo(branch, revno, revision_id)
114
110
 
115
111
 
 
112
# classes in this list should have a "prefix" attribute, against which
 
113
# string specs are matched
 
114
SPEC_TYPES = []
116
115
_revno_regex = None
117
116
 
118
117
 
121
120
 
122
121
    help_txt = """A parsed revision specification.
123
122
 
124
 
    A revision specification is a string, which may be unambiguous about
125
 
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
126
 
    or it may have no prefix, in which case it's tried against several
127
 
    specifier types in sequence to determine what the user meant.
 
123
    A revision specification can be an integer, in which case it is
 
124
    assumed to be a revno (though this will translate negative values
 
125
    into positive ones); or it can be a string, in which case it is
 
126
    parsed for something like 'date:' or 'revid:' etc.
128
127
 
129
128
    Revision specs are an UI element, and they have been moved out
130
129
    of the branch class to leave "back-end" classes unaware of such
136
135
    """
137
136
 
138
137
    prefix = None
139
 
    wants_revision_history = True
140
 
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
141
 
    """Exceptions that RevisionSpec_dwim._match_on will catch.
142
 
 
143
 
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
144
 
    invalid revspec and raises some exception. The exceptions mentioned here
145
 
    will not be reported to the user but simply ignored without stopping the
146
 
    dwim processing.
147
 
    """
 
138
 
 
139
    def __new__(cls, spec, _internal=False):
 
140
        if _internal:
 
141
            return object.__new__(cls, spec, _internal=_internal)
 
142
 
 
143
        symbol_versioning.warn('Creating a RevisionSpec directly has'
 
144
                               ' been deprecated in version 0.11. Use'
 
145
                               ' RevisionSpec.from_string()'
 
146
                               ' instead.',
 
147
                               DeprecationWarning, stacklevel=2)
 
148
        return RevisionSpec.from_string(spec)
148
149
 
149
150
    @staticmethod
150
151
    def from_string(spec):
159
160
 
160
161
        if spec is None:
161
162
            return RevisionSpec(None, _internal=True)
162
 
        match = revspec_registry.get_prefix(spec)
163
 
        if match is not None:
164
 
            spectype, specsuffix = match
165
 
            trace.mutter('Returning RevisionSpec %s for %s',
166
 
                         spectype.__name__, spec)
167
 
            return spectype(spec, _internal=True)
 
163
        for spectype in SPEC_TYPES:
 
164
            if spec.startswith(spectype.prefix):
 
165
                trace.mutter('Returning RevisionSpec %s for %s',
 
166
                             spectype.__name__, spec)
 
167
                return spectype(spec, _internal=True)
168
168
        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
 
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
175
 
            # wait for _match_on to be called.
176
 
            return RevisionSpec_dwim(spec, _internal=True)
 
169
            # RevisionSpec_revno is special cased, because it is the only
 
170
            # one that directly handles plain integers
 
171
            # TODO: This should not be special cased rather it should be
 
172
            # a method invocation on spectype.canparse()
 
173
            global _revno_regex
 
174
            if _revno_regex is None:
 
175
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
176
            if _revno_regex.match(spec) is not None:
 
177
                return RevisionSpec_revno(spec, _internal=True)
 
178
 
 
179
            raise errors.NoSuchRevisionSpec(spec)
177
180
 
178
181
    def __init__(self, spec, _internal=False):
179
182
        """Create a RevisionSpec referring to the Null revision.
183
186
            called directly. Only from RevisionSpec.from_string()
184
187
        """
185
188
        if not _internal:
 
189
            # XXX: Update this after 0.10 is released
186
190
            symbol_versioning.warn('Creating a RevisionSpec directly has'
187
191
                                   ' been deprecated in version 0.11. Use'
188
192
                                   ' RevisionSpec.from_string()'
211
215
 
212
216
    def in_history(self, branch):
213
217
        if branch:
214
 
            if self.wants_revision_history:
215
 
                revs = branch.revision_history()
216
 
            else:
217
 
                revs = None
 
218
            revs = branch.revision_history()
218
219
        else:
219
220
            # this should never trigger.
220
221
            # TODO: make it a deprecated code path. RBC 20060928
247
248
        """
248
249
        return self.in_history(context_branch).rev_id
249
250
 
250
 
    def as_tree(self, context_branch):
251
 
        """Return the tree object for this revisions spec.
252
 
 
253
 
        Some revision specs require a context_branch to be able to determine
254
 
        the revision id and access the repository. Not all specs will make
255
 
        use of it.
256
 
        """
257
 
        return self._as_tree(context_branch)
258
 
 
259
 
    def _as_tree(self, context_branch):
260
 
        """Implementation of as_tree().
261
 
 
262
 
        Classes should override this function to provide appropriate
263
 
        functionality. The default is to just call '.as_revision_id()'
264
 
        and get the revision tree from context_branch's repository.
265
 
        """
266
 
        revision_id = self.as_revision_id(context_branch)
267
 
        return context_branch.repository.revision_tree(revision_id)
268
 
 
269
251
    def __repr__(self):
270
252
        # this is mostly for helping with testing
271
253
        return '<%s %s>' % (self.__class__.__name__,
272
254
                              self.user_spec)
273
 
 
 
255
    
274
256
    def needs_branch(self):
275
257
        """Whether this revision spec needs a branch.
276
258
 
280
262
 
281
263
    def get_branch(self):
282
264
        """When the revision specifier contains a branch location, return it.
283
 
 
 
265
        
284
266
        Otherwise, return None.
285
267
        """
286
268
        return None
288
270
 
289
271
# private API
290
272
 
291
 
class RevisionSpec_dwim(RevisionSpec):
292
 
    """Provides a DWIMish revision specifier lookup.
293
 
 
294
 
    Note that this does not go in the revspec_registry because by definition
295
 
    there is no prefix to identify it.  It's solely called from
296
 
    RevisionSpec.from_string() because the DWIMification happen when _match_on
297
 
    is called so the string describing the revision is kept here until needed.
298
 
    """
299
 
 
300
 
    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
304
 
 
305
 
    def _try_spectype(self, rstype, branch):
306
 
        rs = rstype(self.spec, _internal=True)
307
 
        # Hit in_history to find out if it exists, or we need to try the
308
 
        # next type.
309
 
        return rs.in_history(branch)
310
 
 
311
 
    def _match_on(self, branch, revs):
312
 
        """Run the lookup and see what we can get."""
313
 
 
314
 
        # 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:
319
 
            try:
320
 
                return self._try_spectype(RevisionSpec_revno, branch)
321
 
            except RevisionSpec_revno.dwim_catchable_exceptions:
322
 
                pass
323
 
 
324
 
        # Next see what has been registered
325
 
        for rs_class in dwim_revspecs:
326
 
            try:
327
 
                return self._try_spectype(rs_class, branch)
328
 
            except rs_class.dwim_catchable_exceptions:
329
 
                pass
330
 
 
331
 
        # Well, I dunno what it is. Note that we don't try to keep track of the
332
 
        # first of last exception raised during the DWIM tries as none seems
333
 
        # really relevant.
334
 
        raise errors.InvalidRevisionSpec(self.spec, branch)
335
 
 
336
 
 
337
273
class RevisionSpec_revno(RevisionSpec):
338
274
    """Selects a revision using a number."""
339
275
 
340
276
    help_txt = """Selects a revision using a number.
341
277
 
342
278
    Use an integer to specify a revision in the history of the branch.
343
 
    Optionally a branch can be specified.  A negative number will count
344
 
    from the end of the branch (-1 is the last revision, -2 the previous
345
 
    one). If the negative number is larger than the branch's history, the
346
 
    first revision is returned.
 
279
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
280
    A negative number will count from the end of the branch (-1 is the
 
281
    last revision, -2 the previous one). If the negative number is larger
 
282
    than the branch's history, the first revision is returned.
347
283
    Examples::
348
284
 
349
 
      revno:1                   -> return the first revision of this branch
 
285
      revno:1                   -> return the first revision
350
286
      revno:3:/path/to/branch   -> return the 3rd revision of
351
287
                                   the branch '/path/to/branch'
352
288
      revno:-1                  -> The last revision in a branch.
356
292
                                   your history is very long.
357
293
    """
358
294
    prefix = 'revno:'
359
 
    wants_revision_history = False
360
295
 
361
296
    def _match_on(self, branch, revs):
362
297
        """Lookup a revision by revision number"""
383
318
                dotted = False
384
319
            except ValueError:
385
320
                # dotted decimal. This arguably should not be here
386
 
                # but the from_string method is a little primitive
 
321
                # but the from_string method is a little primitive 
387
322
                # right now - RBC 20060928
388
323
                try:
389
324
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
401
336
            revs_or_none = None
402
337
 
403
338
        if dotted:
 
339
            branch.lock_read()
404
340
            try:
405
 
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
406
 
                    _cache_reverse=True)
407
 
            except errors.NoSuchRevision:
408
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
341
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
 
342
                revisions = [revision_id for revision_id, revno
 
343
                             in revision_id_to_revno.iteritems()
 
344
                             if revno == match_revno]
 
345
            finally:
 
346
                branch.unlock()
 
347
            if len(revisions) != 1:
 
348
                return branch, None, None
409
349
            else:
410
350
                # there is no traditional 'revno' for dotted-decimal revnos.
411
351
                # so for  API compatability we return None.
412
 
                return branch, None, revision_id
 
352
                return branch, None, revisions[0]
413
353
        else:
414
354
            last_revno, last_revision_id = branch.last_revision_info()
415
355
            if revno < 0:
439
379
        else:
440
380
            return self.spec[self.spec.find(':')+1:]
441
381
 
442
 
# Old compatibility
 
382
# Old compatibility 
443
383
RevisionSpec_int = RevisionSpec_revno
444
384
 
 
385
SPEC_TYPES.append(RevisionSpec_revno)
445
386
 
446
387
 
447
388
class RevisionSpec_revid(RevisionSpec):
450
391
    help_txt = """Selects a revision using the revision id.
451
392
 
452
393
    Supply a specific revision id, that can be used to specify any
453
 
    revision id in the ancestry of the branch.
 
394
    revision id in the ancestry of the branch. 
454
395
    Including merges, and pending merges.
455
396
    Examples::
456
397
 
469
410
    def _as_revision_id(self, context_branch):
470
411
        return osutils.safe_revision_id(self.spec, warn=False)
471
412
 
 
413
SPEC_TYPES.append(RevisionSpec_revid)
472
414
 
473
415
 
474
416
class RevisionSpec_last(RevisionSpec):
520
462
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
521
463
        return revision_id
522
464
 
 
465
SPEC_TYPES.append(RevisionSpec_last)
523
466
 
524
467
 
525
468
class RevisionSpec_before(RevisionSpec):
527
470
 
528
471
    help_txt = """Selects the parent of the revision specified.
529
472
 
530
 
    Supply any revision spec to return the parent of that revision.  This is
531
 
    mostly useful when inspecting revisions that are not in the revision history
532
 
    of a branch.
533
 
 
 
473
    Supply any revision spec to return the parent of that revision.
534
474
    It is an error to request the parent of the null revision (before:0).
 
475
    This is mostly useful when inspecting revisions that are not in the
 
476
    revision history of a branch.
535
477
 
536
478
    Examples::
537
479
 
538
480
      before:1913    -> Return the parent of revno 1913 (revno 1912)
539
481
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
540
482
                                            aaaa@bbbb-1234567890
541
 
      bzr diff -r before:1913..1913
542
 
            -> Find the changes between revision 1913 and its parent (1912).
543
 
               (What changes did revision 1913 introduce).
544
 
               This is equivalent to:  bzr diff -c 1913
 
483
      bzr diff -r before:revid:aaaa..revid:aaaa
 
484
            -> Find the changes between revision 'aaaa' and its parent.
 
485
               (what changes did 'aaaa' introduce)
545
486
    """
546
487
 
547
488
    prefix = 'before:'
548
 
 
 
489
    
549
490
    def _match_on(self, branch, revs):
550
491
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
551
492
        if r.revno == 0:
576
517
        base_revspec = RevisionSpec.from_string(self.spec)
577
518
        base_revision_id = base_revspec.as_revision_id(context_branch)
578
519
        if base_revision_id == revision.NULL_REVISION:
579
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
520
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
580
521
                                         'cannot go before the null: revision')
581
522
        context_repo = context_branch.repository
582
523
        context_repo.lock_read()
594
535
                'No parents for revision.')
595
536
        return parents[0]
596
537
 
 
538
SPEC_TYPES.append(RevisionSpec_before)
597
539
 
598
540
 
599
541
class RevisionSpec_tag(RevisionSpec):
605
547
    """
606
548
 
607
549
    prefix = 'tag:'
608
 
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
609
550
 
610
551
    def _match_on(self, branch, revs):
611
552
        # Can raise tags not supported, NoSuchTag, etc
616
557
    def _as_revision_id(self, context_branch):
617
558
        return context_branch.tags.lookup_tag(self.spec)
618
559
 
 
560
SPEC_TYPES.append(RevisionSpec_tag)
619
561
 
620
562
 
621
563
class _RevListToTimestamps(object):
649
591
 
650
592
    One way to display all the changes since yesterday would be::
651
593
 
652
 
        bzr log -r date:yesterday..
 
594
        bzr log -r date:yesterday..-1
653
595
 
654
596
    Examples::
655
597
 
656
598
      date:yesterday            -> select the first revision since yesterday
657
599
      date:2006-08-14,17:10:14  -> select the first revision after
658
600
                                   August 14th, 2006 at 5:10pm.
659
 
    """
 
601
    """    
660
602
    prefix = 'date:'
661
603
    _date_re = re.compile(
662
604
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
722
664
        else:
723
665
            return RevisionInfo(branch, rev + 1)
724
666
 
 
667
SPEC_TYPES.append(RevisionSpec_date)
725
668
 
726
669
 
727
670
class RevisionSpec_ancestor(RevisionSpec):
772
715
            revision_a = revision.ensure_null(branch.last_revision())
773
716
            if revision_a == revision.NULL_REVISION:
774
717
                raise errors.NoCommits(branch)
775
 
            if other_location == '':
776
 
                other_location = branch.get_parent()
777
718
            other_branch = Branch.open(other_location)
778
719
            other_branch.lock_read()
779
720
            try:
791
732
            branch.unlock()
792
733
 
793
734
 
 
735
SPEC_TYPES.append(RevisionSpec_ancestor)
794
736
 
795
737
 
796
738
class RevisionSpec_branch(RevisionSpec):
805
747
      branch:/path/to/branch
806
748
    """
807
749
    prefix = 'branch:'
808
 
    dwim_catchable_exceptions = (errors.NotBranchError,)
809
750
 
810
751
    def _match_on(self, branch, revs):
811
752
        from bzrlib.branch import Branch
826
767
        other_branch = Branch.open(self.spec)
827
768
        last_revision = other_branch.last_revision()
828
769
        last_revision = revision.ensure_null(last_revision)
829
 
        context_branch.fetch(other_branch, last_revision)
830
770
        if last_revision == revision.NULL_REVISION:
831
771
            raise errors.NoCommits(other_branch)
832
772
        return last_revision
833
773
 
834
 
    def _as_tree(self, context_branch):
835
 
        from bzrlib.branch import Branch
836
 
        other_branch = Branch.open(self.spec)
837
 
        last_revision = other_branch.last_revision()
838
 
        last_revision = revision.ensure_null(last_revision)
839
 
        if last_revision == revision.NULL_REVISION:
840
 
            raise errors.NoCommits(other_branch)
841
 
        return other_branch.repository.revision_tree(last_revision)
842
 
 
 
774
SPEC_TYPES.append(RevisionSpec_branch)
843
775
 
844
776
 
845
777
class RevisionSpec_submit(RevisionSpec_ancestor):
849
781
 
850
782
    Diffing against this shows all the changes that were made in this branch,
851
783
    and is a good predictor of what merge will do.  The submit branch is
852
 
    used by the bundle and merge directive commands.  If no submit branch
 
784
    used by the bundle and merge directive comands.  If no submit branch
853
785
    is specified, the parent branch is used instead.
854
786
 
855
787
    The common ancestor is the last revision that existed in both
884
816
            self._get_submit_location(context_branch))
885
817
 
886
818
 
887
 
# The order in which we want to DWIM a revision spec without any prefix.
888
 
# revno is always tried first and isn't listed here, this is used by
889
 
# 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
 
 
897
 
 
898
 
revspec_registry = registry.Registry()
899
 
def _register_revspec(revspec):
900
 
    revspec_registry.register(revspec.prefix, revspec)
901
 
 
902
 
_register_revspec(RevisionSpec_revno)
903
 
_register_revspec(RevisionSpec_revid)
904
 
_register_revspec(RevisionSpec_last)
905
 
_register_revspec(RevisionSpec_before)
906
 
_register_revspec(RevisionSpec_tag)
907
 
_register_revspec(RevisionSpec_date)
908
 
_register_revspec(RevisionSpec_ancestor)
909
 
_register_revspec(RevisionSpec_branch)
910
 
_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", [])
 
819
SPEC_TYPES.append(RevisionSpec_submit)