~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Pool
  • Date: 2010-01-31 16:23:09 UTC
  • mto: (4999.3.1 apport)
  • mto: This revision was merged to the branch mainline in revision 5002.
  • Revision ID: mbp@sourcefrog.net-20100131162309-qrhsp7h9akni3qwb
comment

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
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
 
18
import re
 
19
 
18
20
from bzrlib.lazy_import import lazy_import
19
21
lazy_import(globals(), """
20
22
import bisect
21
23
import datetime
 
24
""")
22
25
 
23
26
from bzrlib import (
24
 
    branch as _mod_branch,
 
27
    errors,
25
28
    osutils,
 
29
    registry,
26
30
    revision,
27
31
    symbol_versioning,
28
 
    workingtree,
29
 
    )
30
 
""")
31
 
 
32
 
from bzrlib import (
33
 
    errors,
34
 
    lazy_regex,
35
 
    registry,
36
32
    trace,
37
33
    )
38
34
 
117
113
        return RevisionInfo(branch, revno, revision_id)
118
114
 
119
115
 
 
116
# classes in this list should have a "prefix" attribute, against which
 
117
# string specs are matched
 
118
_revno_regex = None
 
119
 
 
120
 
120
121
class RevisionSpec(object):
121
122
    """A parsed revision specification."""
122
123
 
123
124
    help_txt = """A parsed revision specification.
124
125
 
125
 
    A revision specification is a string, which may be unambiguous about
126
 
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
127
 
    or it may have no prefix, in which case it's tried against several
128
 
    specifier types in sequence to determine what the user meant.
 
126
    A revision specification can be an integer, in which case it is
 
127
    assumed to be a revno (though this will translate negative values
 
128
    into positive ones); or it can be a string, in which case it is
 
129
    parsed for something like 'date:' or 'revid:' etc.
129
130
 
130
131
    Revision specs are an UI element, and they have been moved out
131
132
    of the branch class to leave "back-end" classes unaware of such
138
139
 
139
140
    prefix = None
140
141
    wants_revision_history = True
141
 
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
142
 
    """Exceptions that RevisionSpec_dwim._match_on will catch.
143
 
 
144
 
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
145
 
    invalid revspec and raises some exception. The exceptions mentioned here
146
 
    will not be reported to the user but simply ignored without stopping the
147
 
    dwim processing.
148
 
    """
149
142
 
150
143
    @staticmethod
151
144
    def from_string(spec):
167
160
                         spectype.__name__, spec)
168
161
            return spectype(spec, _internal=True)
169
162
        else:
170
 
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
171
 
            # wait for _match_on to be called.
172
 
            return RevisionSpec_dwim(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
            # RevisionSpec_revno is special cased, because it is the only
 
169
            # one that directly handles plain integers
 
170
            # TODO: This should not be special cased rather it should be
 
171
            # a method invocation on spectype.canparse()
 
172
            global _revno_regex
 
173
            if _revno_regex is None:
 
174
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
175
            if _revno_regex.match(spec) is not None:
 
176
                return RevisionSpec_revno(spec, _internal=True)
 
177
 
 
178
            raise errors.NoSuchRevisionSpec(spec)
173
179
 
174
180
    def __init__(self, spec, _internal=False):
175
181
        """Create a RevisionSpec referring to the Null revision.
284
290
 
285
291
# private API
286
292
 
287
 
class RevisionSpec_dwim(RevisionSpec):
288
 
    """Provides a DWIMish revision specifier lookup.
289
 
 
290
 
    Note that this does not go in the revspec_registry because by definition
291
 
    there is no prefix to identify it.  It's solely called from
292
 
    RevisionSpec.from_string() because the DWIMification happen when _match_on
293
 
    is called so the string describing the revision is kept here until needed.
294
 
    """
295
 
 
296
 
    help_txt = None
297
 
    # We don't need to build the revision history ourself, that's delegated to
298
 
    # each revspec we try.
299
 
    wants_revision_history = False
300
 
 
301
 
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
302
 
 
303
 
    # The revspecs to try
304
 
    _possible_revspecs = []
305
 
 
306
 
    def _try_spectype(self, rstype, branch):
307
 
        rs = rstype(self.spec, _internal=True)
308
 
        # Hit in_history to find out if it exists, or we need to try the
309
 
        # next type.
310
 
        return rs.in_history(branch)
311
 
 
312
 
    def _match_on(self, branch, revs):
313
 
        """Run the lookup and see what we can get."""
314
 
 
315
 
        # First, see if it's a revno
316
 
        if self._revno_regex.match(self.spec) is not None:
317
 
            try:
318
 
                return self._try_spectype(RevisionSpec_revno, branch)
319
 
            except RevisionSpec_revno.dwim_catchable_exceptions:
320
 
                pass
321
 
 
322
 
        # Next see what has been registered
323
 
        for objgetter in self._possible_revspecs:
324
 
            rs_class = objgetter.get_obj()
325
 
            try:
326
 
                return self._try_spectype(rs_class, branch)
327
 
            except rs_class.dwim_catchable_exceptions:
328
 
                pass
329
 
 
330
 
        # Try the old (deprecated) dwim list:
331
 
        for rs_class in dwim_revspecs:
332
 
            try:
333
 
                return self._try_spectype(rs_class, branch)
334
 
            except rs_class.dwim_catchable_exceptions:
335
 
                pass
336
 
 
337
 
        # Well, I dunno what it is. Note that we don't try to keep track of the
338
 
        # first of last exception raised during the DWIM tries as none seems
339
 
        # really relevant.
340
 
        raise errors.InvalidRevisionSpec(self.spec, branch)
341
 
 
342
 
    @classmethod
343
 
    def append_possible_revspec(cls, revspec):
344
 
        """Append a possible DWIM revspec.
345
 
 
346
 
        :param revspec: Revision spec to try.
347
 
        """
348
 
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
349
 
 
350
 
    @classmethod
351
 
    def append_possible_lazy_revspec(cls, module_name, member_name):
352
 
        """Append a possible lazily loaded DWIM revspec.
353
 
 
354
 
        :param module_name: Name of the module with the revspec
355
 
        :param member_name: Name of the revspec within the module
356
 
        """
357
 
        cls._possible_revspecs.append(
358
 
            registry._LazyObjectGetter(module_name, member_name))
359
 
 
360
 
 
361
293
class RevisionSpec_revno(RevisionSpec):
362
294
    """Selects a revision using a number."""
363
295
 
364
296
    help_txt = """Selects a revision using a number.
365
297
 
366
298
    Use an integer to specify a revision in the history of the branch.
367
 
    Optionally a branch can be specified.  A negative number will count
368
 
    from the end of the branch (-1 is the last revision, -2 the previous
369
 
    one). If the negative number is larger than the branch's history, the
370
 
    first revision is returned.
 
299
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
300
    A negative number will count from the end of the branch (-1 is the
 
301
    last revision, -2 the previous one). If the negative number is larger
 
302
    than the branch's history, the first revision is returned.
371
303
    Examples::
372
304
 
373
305
      revno:1                   -> return the first revision of this branch
468
400
 
469
401
 
470
402
 
471
 
class RevisionIDSpec(RevisionSpec):
472
 
 
473
 
    def _match_on(self, branch, revs):
474
 
        revision_id = self.as_revision_id(branch)
475
 
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
476
 
 
477
 
 
478
 
class RevisionSpec_revid(RevisionIDSpec):
 
403
class RevisionSpec_revid(RevisionSpec):
479
404
    """Selects a revision using the revision id."""
480
405
 
481
406
    help_txt = """Selects a revision using the revision id.
490
415
 
491
416
    prefix = 'revid:'
492
417
 
493
 
    def _as_revision_id(self, context_branch):
 
418
    def _match_on(self, branch, revs):
494
419
        # self.spec comes straight from parsing the command line arguments,
495
420
        # so we expect it to be a Unicode string. Switch it to the internal
496
421
        # representation.
 
422
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
423
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
424
 
 
425
    def _as_revision_id(self, context_branch):
497
426
        return osutils.safe_revision_id(self.spec, warn=False)
498
427
 
499
428
 
632
561
    """
633
562
 
634
563
    prefix = 'tag:'
635
 
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
636
564
 
637
565
    def _match_on(self, branch, revs):
638
566
        # Can raise tags not supported, NoSuchTag, etc
685
613
                                   August 14th, 2006 at 5:10pm.
686
614
    """
687
615
    prefix = 'date:'
688
 
    _date_regex = lazy_regex.lazy_compile(
 
616
    _date_re = re.compile(
689
617
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
690
618
            r'(,|T)?\s*'
691
619
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
709
637
        elif self.spec.lower() == 'tomorrow':
710
638
            dt = today + datetime.timedelta(days=1)
711
639
        else:
712
 
            m = self._date_regex.match(self.spec)
 
640
            m = self._date_re.match(self.spec)
713
641
            if not m or (not m.group('date') and not m.group('time')):
714
642
                raise errors.InvalidRevisionSpec(self.user_spec,
715
643
                                                 branch, 'invalid date')
832
760
      branch:/path/to/branch
833
761
    """
834
762
    prefix = 'branch:'
835
 
    dwim_catchable_exceptions = (errors.NotBranchError,)
836
763
 
837
764
    def _match_on(self, branch, revs):
838
765
        from bzrlib.branch import Branch
840
767
        revision_b = other_branch.last_revision()
841
768
        if revision_b in (None, revision.NULL_REVISION):
842
769
            raise errors.NoCommits(other_branch)
843
 
        if branch is None:
844
 
            branch = other_branch
845
 
        else:
846
 
            try:
847
 
                # pull in the remote revisions so we can diff
848
 
                branch.fetch(other_branch, revision_b)
849
 
            except errors.ReadOnlyError:
850
 
                branch = other_branch
 
770
        # pull in the remote revisions so we can diff
 
771
        branch.fetch(other_branch, revision_b)
851
772
        try:
852
773
            revno = branch.revision_id_to_revno(revision_b)
853
774
        except errors.NoSuchRevision:
873
794
            raise errors.NoCommits(other_branch)
874
795
        return other_branch.repository.revision_tree(last_revision)
875
796
 
876
 
    def needs_branch(self):
877
 
        return False
878
 
 
879
 
    def get_branch(self):
880
 
        return self.spec
881
 
 
882
797
 
883
798
 
884
799
class RevisionSpec_submit(RevisionSpec_ancestor):
923
838
            self._get_submit_location(context_branch))
924
839
 
925
840
 
926
 
class RevisionSpec_annotate(RevisionIDSpec):
927
 
 
928
 
    prefix = 'annotate:'
929
 
 
930
 
    help_txt = """Select the revision that last modified the specified line.
931
 
 
932
 
    Select the revision that last modified the specified line.  Line is
933
 
    specified as path:number.  Path is a relative path to the file.  Numbers
934
 
    start at 1, and are relative to the current version, not the last-
935
 
    committed version of the file.
936
 
    """
937
 
 
938
 
    def _raise_invalid(self, numstring, context_branch):
939
 
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
940
 
            'No such line: %s' % numstring)
941
 
 
942
 
    def _as_revision_id(self, context_branch):
943
 
        path, numstring = self.spec.rsplit(':', 1)
944
 
        try:
945
 
            index = int(numstring) - 1
946
 
        except ValueError:
947
 
            self._raise_invalid(numstring, context_branch)
948
 
        tree, file_path = workingtree.WorkingTree.open_containing(path)
949
 
        tree.lock_read()
950
 
        try:
951
 
            file_id = tree.path2id(file_path)
952
 
            if file_id is None:
953
 
                raise errors.InvalidRevisionSpec(self.user_spec,
954
 
                    context_branch, "File '%s' is not versioned." %
955
 
                    file_path)
956
 
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
957
 
        finally:
958
 
            tree.unlock()
959
 
        try:
960
 
            revision_id = revision_ids[index]
961
 
        except IndexError:
962
 
            self._raise_invalid(numstring, context_branch)
963
 
        if revision_id == revision.CURRENT_REVISION:
964
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
965
 
                'Line %s has not been committed.' % numstring)
966
 
        return revision_id
967
 
 
968
 
 
969
 
class RevisionSpec_mainline(RevisionIDSpec):
970
 
 
971
 
    help_txt = """Select mainline revision that merged the specified revision.
972
 
 
973
 
    Select the revision that merged the specified revision into mainline.
974
 
    """
975
 
 
976
 
    prefix = 'mainline:'
977
 
 
978
 
    def _as_revision_id(self, context_branch):
979
 
        revspec = RevisionSpec.from_string(self.spec)
980
 
        if revspec.get_branch() is None:
981
 
            spec_branch = context_branch
982
 
        else:
983
 
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
984
 
        revision_id = revspec.as_revision_id(spec_branch)
985
 
        graph = context_branch.repository.get_graph()
986
 
        result = graph.find_lefthand_merger(revision_id,
987
 
                                            context_branch.last_revision())
988
 
        if result is None:
989
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
990
 
        return result
991
 
 
992
 
 
993
 
# The order in which we want to DWIM a revision spec without any prefix.
994
 
# revno is always tried first and isn't listed here, this is used by
995
 
# RevisionSpec_dwim._match_on
996
 
dwim_revspecs = symbol_versioning.deprecated_list(
997
 
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])
998
 
 
999
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
1000
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
1001
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
1002
 
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
1003
 
 
1004
841
revspec_registry = registry.Registry()
1005
842
def _register_revspec(revspec):
1006
843
    revspec_registry.register(revspec.prefix, revspec)
1014
851
_register_revspec(RevisionSpec_ancestor)
1015
852
_register_revspec(RevisionSpec_branch)
1016
853
_register_revspec(RevisionSpec_submit)
1017
 
_register_revspec(RevisionSpec_annotate)
1018
 
_register_revspec(RevisionSpec_mainline)
 
854
 
 
855
SPEC_TYPES = symbol_versioning.deprecated_list(
 
856
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])