/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 bzrlib/revisionspec.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
 
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(), """
18
22
import bisect
19
23
import datetime
20
 
import re
 
24
""")
21
25
 
22
26
from bzrlib import (
23
27
    errors,
24
28
    osutils,
 
29
    registry,
25
30
    revision,
26
31
    symbol_versioning,
27
32
    trace,
28
 
    tsort,
29
33
    )
30
34
 
31
35
 
109
113
        return RevisionInfo(branch, revno, revision_id)
110
114
 
111
115
 
112
 
# classes in this list should have a "prefix" attribute, against which
113
 
# string specs are matched
114
 
SPEC_TYPES = []
115
116
_revno_regex = None
116
117
 
117
118
 
120
121
 
121
122
    help_txt = """A parsed revision specification.
122
123
 
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.
 
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.
127
128
 
128
129
    Revision specs are an UI element, and they have been moved out
129
130
    of the branch class to leave "back-end" classes unaware of such
135
136
    """
136
137
 
137
138
    prefix = None
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)
 
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
    """
149
148
 
150
149
    @staticmethod
151
150
    def from_string(spec):
160
159
 
161
160
        if spec is None:
162
161
            return RevisionSpec(None, _internal=True)
163
 
 
164
 
        assert isinstance(spec, basestring), \
165
 
            "You should only supply strings not %s" % (type(spec),)
166
 
 
167
 
        for spectype in SPEC_TYPES:
168
 
            if spec.startswith(spectype.prefix):
169
 
                trace.mutter('Returning RevisionSpec %s for %s',
170
 
                             spectype.__name__, spec)
171
 
                return spectype(spec, _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)
172
168
        else:
173
 
            # RevisionSpec_revno is special cased, because it is the only
174
 
            # one that directly handles plain integers
175
 
            # TODO: This should not be special cased rather it should be
176
 
            # a method invocation on spectype.canparse()
177
 
            global _revno_regex
178
 
            if _revno_regex is None:
179
 
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
180
 
            if _revno_regex.match(spec) is not None:
181
 
                return RevisionSpec_revno(spec, _internal=True)
182
 
 
183
 
            raise errors.NoSuchRevisionSpec(spec)
 
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)
184
177
 
185
178
    def __init__(self, spec, _internal=False):
186
179
        """Create a RevisionSpec referring to the Null revision.
190
183
            called directly. Only from RevisionSpec.from_string()
191
184
        """
192
185
        if not _internal:
193
 
            # XXX: Update this after 0.10 is released
194
186
            symbol_versioning.warn('Creating a RevisionSpec directly has'
195
187
                                   ' been deprecated in version 0.11. Use'
196
188
                                   ' RevisionSpec.from_string()'
219
211
 
220
212
    def in_history(self, branch):
221
213
        if branch:
222
 
            revs = branch.revision_history()
 
214
            if self.wants_revision_history:
 
215
                revs = branch.revision_history()
 
216
            else:
 
217
                revs = None
223
218
        else:
224
219
            # this should never trigger.
225
220
            # TODO: make it a deprecated code path. RBC 20060928
252
247
        """
253
248
        return self.in_history(context_branch).rev_id
254
249
 
 
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
 
255
269
    def __repr__(self):
256
270
        # this is mostly for helping with testing
257
271
        return '<%s %s>' % (self.__class__.__name__,
258
272
                              self.user_spec)
259
 
    
 
273
 
260
274
    def needs_branch(self):
261
275
        """Whether this revision spec needs a branch.
262
276
 
266
280
 
267
281
    def get_branch(self):
268
282
        """When the revision specifier contains a branch location, return it.
269
 
        
 
283
 
270
284
        Otherwise, return None.
271
285
        """
272
286
        return None
274
288
 
275
289
# private API
276
290
 
 
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
 
277
337
class RevisionSpec_revno(RevisionSpec):
278
338
    """Selects a revision using a number."""
279
339
 
280
340
    help_txt = """Selects a revision using a number.
281
341
 
282
342
    Use an integer to specify a revision in the history of the branch.
283
 
    Optionally a branch can be specified. The 'revno:' prefix is optional.
284
 
    A negative number will count from the end of the branch (-1 is the
285
 
    last revision, -2 the previous one). If the negative number is larger
286
 
    than the branch's history, the first revision is returned.
 
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.
287
347
    Examples::
288
348
 
289
 
      revno:1                   -> return the first revision
 
349
      revno:1                   -> return the first revision of this branch
290
350
      revno:3:/path/to/branch   -> return the 3rd revision of
291
351
                                   the branch '/path/to/branch'
292
352
      revno:-1                  -> The last revision in a branch.
296
356
                                   your history is very long.
297
357
    """
298
358
    prefix = 'revno:'
 
359
    wants_revision_history = False
299
360
 
300
361
    def _match_on(self, branch, revs):
301
362
        """Lookup a revision by revision number"""
322
383
                dotted = False
323
384
            except ValueError:
324
385
                # dotted decimal. This arguably should not be here
325
 
                # but the from_string method is a little primitive 
 
386
                # but the from_string method is a little primitive
326
387
                # right now - RBC 20060928
327
388
                try:
328
389
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
340
401
            revs_or_none = None
341
402
 
342
403
        if dotted:
343
 
            branch.lock_read()
344
404
            try:
345
 
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
346
 
                revisions = [revision_id for revision_id, revno
347
 
                             in revision_id_to_revno.iteritems()
348
 
                             if revno == match_revno]
349
 
            finally:
350
 
                branch.unlock()
351
 
            if len(revisions) != 1:
352
 
                return branch, None, None
 
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)
353
409
            else:
354
410
                # there is no traditional 'revno' for dotted-decimal revnos.
355
411
                # so for  API compatability we return None.
356
 
                return branch, None, revisions[0]
 
412
                return branch, None, revision_id
357
413
        else:
358
414
            last_revno, last_revision_id = branch.last_revision_info()
359
415
            if revno < 0:
383
439
        else:
384
440
            return self.spec[self.spec.find(':')+1:]
385
441
 
386
 
# Old compatibility 
 
442
# Old compatibility
387
443
RevisionSpec_int = RevisionSpec_revno
388
444
 
389
 
SPEC_TYPES.append(RevisionSpec_revno)
390
445
 
391
446
 
392
447
class RevisionSpec_revid(RevisionSpec):
395
450
    help_txt = """Selects a revision using the revision id.
396
451
 
397
452
    Supply a specific revision id, that can be used to specify any
398
 
    revision id in the ancestry of the branch. 
 
453
    revision id in the ancestry of the branch.
399
454
    Including merges, and pending merges.
400
455
    Examples::
401
456
 
414
469
    def _as_revision_id(self, context_branch):
415
470
        return osutils.safe_revision_id(self.spec, warn=False)
416
471
 
417
 
SPEC_TYPES.append(RevisionSpec_revid)
418
472
 
419
473
 
420
474
class RevisionSpec_last(RevisionSpec):
466
520
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
467
521
        return revision_id
468
522
 
469
 
SPEC_TYPES.append(RevisionSpec_last)
470
523
 
471
524
 
472
525
class RevisionSpec_before(RevisionSpec):
474
527
 
475
528
    help_txt = """Selects the parent of the revision specified.
476
529
 
477
 
    Supply any revision spec to return the parent of that revision.
 
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
 
478
534
    It is an error to request the parent of the null revision (before:0).
479
 
    This is mostly useful when inspecting revisions that are not in the
480
 
    revision history of a branch.
481
535
 
482
536
    Examples::
483
537
 
484
538
      before:1913    -> Return the parent of revno 1913 (revno 1912)
485
539
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
486
540
                                            aaaa@bbbb-1234567890
487
 
      bzr diff -r before:revid:aaaa..revid:aaaa
488
 
            -> Find the changes between revision 'aaaa' and its parent.
489
 
               (what changes did 'aaaa' introduce)
 
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
490
545
    """
491
546
 
492
547
    prefix = 'before:'
493
 
    
 
548
 
494
549
    def _match_on(self, branch, revs):
495
550
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
496
551
        if r.revno == 0:
521
576
        base_revspec = RevisionSpec.from_string(self.spec)
522
577
        base_revision_id = base_revspec.as_revision_id(context_branch)
523
578
        if base_revision_id == revision.NULL_REVISION:
524
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
579
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
525
580
                                         'cannot go before the null: revision')
526
581
        context_repo = context_branch.repository
527
582
        context_repo.lock_read()
539
594
                'No parents for revision.')
540
595
        return parents[0]
541
596
 
542
 
SPEC_TYPES.append(RevisionSpec_before)
543
597
 
544
598
 
545
599
class RevisionSpec_tag(RevisionSpec):
551
605
    """
552
606
 
553
607
    prefix = 'tag:'
 
608
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
554
609
 
555
610
    def _match_on(self, branch, revs):
556
611
        # Can raise tags not supported, NoSuchTag, etc
561
616
    def _as_revision_id(self, context_branch):
562
617
        return context_branch.tags.lookup_tag(self.spec)
563
618
 
564
 
SPEC_TYPES.append(RevisionSpec_tag)
565
619
 
566
620
 
567
621
class _RevListToTimestamps(object):
595
649
 
596
650
    One way to display all the changes since yesterday would be::
597
651
 
598
 
        bzr log -r date:yesterday..-1
 
652
        bzr log -r date:yesterday..
599
653
 
600
654
    Examples::
601
655
 
602
656
      date:yesterday            -> select the first revision since yesterday
603
657
      date:2006-08-14,17:10:14  -> select the first revision after
604
658
                                   August 14th, 2006 at 5:10pm.
605
 
    """    
 
659
    """
606
660
    prefix = 'date:'
607
661
    _date_re = re.compile(
608
662
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
668
722
        else:
669
723
            return RevisionInfo(branch, rev + 1)
670
724
 
671
 
SPEC_TYPES.append(RevisionSpec_date)
672
725
 
673
726
 
674
727
class RevisionSpec_ancestor(RevisionSpec):
719
772
            revision_a = revision.ensure_null(branch.last_revision())
720
773
            if revision_a == revision.NULL_REVISION:
721
774
                raise errors.NoCommits(branch)
 
775
            if other_location == '':
 
776
                other_location = branch.get_parent()
722
777
            other_branch = Branch.open(other_location)
723
778
            other_branch.lock_read()
724
779
            try:
736
791
            branch.unlock()
737
792
 
738
793
 
739
 
SPEC_TYPES.append(RevisionSpec_ancestor)
740
794
 
741
795
 
742
796
class RevisionSpec_branch(RevisionSpec):
751
805
      branch:/path/to/branch
752
806
    """
753
807
    prefix = 'branch:'
 
808
    dwim_catchable_exceptions = (errors.NotBranchError,)
754
809
 
755
810
    def _match_on(self, branch, revs):
756
811
        from bzrlib.branch import Branch
771
826
        other_branch = Branch.open(self.spec)
772
827
        last_revision = other_branch.last_revision()
773
828
        last_revision = revision.ensure_null(last_revision)
 
829
        context_branch.fetch(other_branch, last_revision)
774
830
        if last_revision == revision.NULL_REVISION:
775
831
            raise errors.NoCommits(other_branch)
776
832
        return last_revision
777
833
 
778
 
SPEC_TYPES.append(RevisionSpec_branch)
 
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
 
779
843
 
780
844
 
781
845
class RevisionSpec_submit(RevisionSpec_ancestor):
785
849
 
786
850
    Diffing against this shows all the changes that were made in this branch,
787
851
    and is a good predictor of what merge will do.  The submit branch is
788
 
    used by the bundle and merge directive comands.  If no submit branch
 
852
    used by the bundle and merge directive commands.  If no submit branch
789
853
    is specified, the parent branch is used instead.
790
854
 
791
855
    The common ancestor is the last revision that existed in both
820
884
            self._get_submit_location(context_branch))
821
885
 
822
886
 
823
 
SPEC_TYPES.append(RevisionSpec_submit)
 
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", [])