~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

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
 
 
18
 
import re
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
19
17
 
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
 
113
118
        return RevisionInfo(branch, revno, revision_id)
114
119
 
115
120
 
116
 
# classes in this list should have a "prefix" attribute, against which
117
 
# string specs are matched
118
 
_revno_regex = None
119
 
 
120
 
 
121
121
class RevisionSpec(object):
122
122
    """A parsed revision specification."""
123
123
 
124
124
    help_txt = """A parsed revision specification.
125
125
 
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.
 
126
    A revision specification is a string, which may be unambiguous about
 
127
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
 
128
    or it may have no prefix, in which case it's tried against several
 
129
    specifier types in sequence to determine what the user meant.
130
130
 
131
131
    Revision specs are an UI element, and they have been moved out
132
132
    of the branch class to leave "back-end" classes unaware of such
139
139
 
140
140
    prefix = None
141
141
    wants_revision_history = True
 
142
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
 
143
    """Exceptions that RevisionSpec_dwim._match_on will catch.
 
144
 
 
145
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
 
146
    invalid revspec and raises some exception. The exceptions mentioned here
 
147
    will not be reported to the user but simply ignored without stopping the
 
148
    dwim processing.
 
149
    """
142
150
 
143
151
    @staticmethod
144
152
    def from_string(spec):
160
168
                         spectype.__name__, spec)
161
169
            return spectype(spec, _internal=True)
162
170
        else:
163
 
            for spectype in SPEC_TYPES:
164
 
                trace.mutter('Returning RevisionSpec %s for %s',
165
 
                             spectype.__name__, spec)
166
 
                if spec.startswith(spectype.prefix):
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)
 
171
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
 
172
            # wait for _match_on to be called.
 
173
            return RevisionSpec_dwim(spec, _internal=True)
179
174
 
180
175
    def __init__(self, spec, _internal=False):
181
176
        """Create a RevisionSpec referring to the Null revision.
185
180
            called directly. Only from RevisionSpec.from_string()
186
181
        """
187
182
        if not _internal:
188
 
            # XXX: Update this after 0.10 is released
189
183
            symbol_versioning.warn('Creating a RevisionSpec directly has'
190
184
                                   ' been deprecated in version 0.11. Use'
191
185
                                   ' RevisionSpec.from_string()'
273
267
        # this is mostly for helping with testing
274
268
        return '<%s %s>' % (self.__class__.__name__,
275
269
                              self.user_spec)
276
 
    
 
270
 
277
271
    def needs_branch(self):
278
272
        """Whether this revision spec needs a branch.
279
273
 
283
277
 
284
278
    def get_branch(self):
285
279
        """When the revision specifier contains a branch location, return it.
286
 
        
 
280
 
287
281
        Otherwise, return None.
288
282
        """
289
283
        return None
291
285
 
292
286
# private API
293
287
 
 
288
class RevisionSpec_dwim(RevisionSpec):
 
289
    """Provides a DWIMish revision specifier lookup.
 
290
 
 
291
    Note that this does not go in the revspec_registry because by definition
 
292
    there is no prefix to identify it.  It's solely called from
 
293
    RevisionSpec.from_string() because the DWIMification happen when _match_on
 
294
    is called so the string describing the revision is kept here until needed.
 
295
    """
 
296
 
 
297
    help_txt = None
 
298
    # We don't need to build the revision history ourself, that's delegated to
 
299
    # each revspec we try.
 
300
    wants_revision_history = False
 
301
 
 
302
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
303
 
 
304
    # The revspecs to try
 
305
    _possible_revspecs = []
 
306
 
 
307
    def _try_spectype(self, rstype, branch):
 
308
        rs = rstype(self.spec, _internal=True)
 
309
        # Hit in_history to find out if it exists, or we need to try the
 
310
        # next type.
 
311
        return rs.in_history(branch)
 
312
 
 
313
    def _match_on(self, branch, revs):
 
314
        """Run the lookup and see what we can get."""
 
315
 
 
316
        # First, see if it's a revno
 
317
        if self._revno_regex.match(self.spec) is not None:
 
318
            try:
 
319
                return self._try_spectype(RevisionSpec_revno, branch)
 
320
            except RevisionSpec_revno.dwim_catchable_exceptions:
 
321
                pass
 
322
 
 
323
        # Next see what has been registered
 
324
        for objgetter in self._possible_revspecs:
 
325
            rs_class = objgetter.get_obj()
 
326
            try:
 
327
                return self._try_spectype(rs_class, branch)
 
328
            except rs_class.dwim_catchable_exceptions:
 
329
                pass
 
330
 
 
331
        # Try the old (deprecated) dwim list:
 
332
        for rs_class in dwim_revspecs:
 
333
            try:
 
334
                return self._try_spectype(rs_class, branch)
 
335
            except rs_class.dwim_catchable_exceptions:
 
336
                pass
 
337
 
 
338
        # Well, I dunno what it is. Note that we don't try to keep track of the
 
339
        # first of last exception raised during the DWIM tries as none seems
 
340
        # really relevant.
 
341
        raise errors.InvalidRevisionSpec(self.spec, branch)
 
342
 
 
343
    @classmethod
 
344
    def append_possible_revspec(cls, revspec):
 
345
        """Append a possible DWIM revspec.
 
346
 
 
347
        :param revspec: Revision spec to try.
 
348
        """
 
349
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
 
350
 
 
351
    @classmethod
 
352
    def append_possible_lazy_revspec(cls, module_name, member_name):
 
353
        """Append a possible lazily loaded DWIM revspec.
 
354
 
 
355
        :param module_name: Name of the module with the revspec
 
356
        :param member_name: Name of the revspec within the module
 
357
        """
 
358
        cls._possible_revspecs.append(
 
359
            registry._LazyObjectGetter(module_name, member_name))
 
360
 
 
361
 
294
362
class RevisionSpec_revno(RevisionSpec):
295
363
    """Selects a revision using a number."""
296
364
 
297
365
    help_txt = """Selects a revision using a number.
298
366
 
299
367
    Use an integer to specify a revision in the history of the branch.
300
 
    Optionally a branch can be specified. The 'revno:' prefix is optional.
301
 
    A negative number will count from the end of the branch (-1 is the
302
 
    last revision, -2 the previous one). If the negative number is larger
303
 
    than the branch's history, the first revision is returned.
 
368
    Optionally a branch can be specified.  A negative number will count
 
369
    from the end of the branch (-1 is the last revision, -2 the previous
 
370
    one). If the negative number is larger than the branch's history, the
 
371
    first revision is returned.
304
372
    Examples::
305
373
 
306
374
      revno:1                   -> return the first revision of this branch
340
408
                dotted = False
341
409
            except ValueError:
342
410
                # dotted decimal. This arguably should not be here
343
 
                # but the from_string method is a little primitive 
 
411
                # but the from_string method is a little primitive
344
412
                # right now - RBC 20060928
345
413
                try:
346
414
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
396
464
        else:
397
465
            return self.spec[self.spec.find(':')+1:]
398
466
 
399
 
# Old compatibility 
 
467
# Old compatibility
400
468
RevisionSpec_int = RevisionSpec_revno
401
469
 
402
470
 
403
471
 
404
 
class RevisionSpec_revid(RevisionSpec):
 
472
class RevisionIDSpec(RevisionSpec):
 
473
 
 
474
    def _match_on(self, branch, revs):
 
475
        revision_id = self.as_revision_id(branch)
 
476
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
477
 
 
478
 
 
479
class RevisionSpec_revid(RevisionIDSpec):
405
480
    """Selects a revision using the revision id."""
406
481
 
407
482
    help_txt = """Selects a revision using the revision id.
408
483
 
409
484
    Supply a specific revision id, that can be used to specify any
410
 
    revision id in the ancestry of the branch. 
 
485
    revision id in the ancestry of the branch.
411
486
    Including merges, and pending merges.
412
487
    Examples::
413
488
 
416
491
 
417
492
    prefix = 'revid:'
418
493
 
419
 
    def _match_on(self, branch, revs):
 
494
    def _as_revision_id(self, context_branch):
420
495
        # self.spec comes straight from parsing the command line arguments,
421
496
        # so we expect it to be a Unicode string. Switch it to the internal
422
497
        # representation.
423
 
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
424
 
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
425
 
 
426
 
    def _as_revision_id(self, context_branch):
427
498
        return osutils.safe_revision_id(self.spec, warn=False)
428
499
 
429
500
 
502
573
    """
503
574
 
504
575
    prefix = 'before:'
505
 
    
 
576
 
506
577
    def _match_on(self, branch, revs):
507
578
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
508
579
        if r.revno == 0:
562
633
    """
563
634
 
564
635
    prefix = 'tag:'
 
636
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
565
637
 
566
638
    def _match_on(self, branch, revs):
567
639
        # Can raise tags not supported, NoSuchTag, etc
612
684
      date:yesterday            -> select the first revision since yesterday
613
685
      date:2006-08-14,17:10:14  -> select the first revision after
614
686
                                   August 14th, 2006 at 5:10pm.
615
 
    """    
 
687
    """
616
688
    prefix = 'date:'
617
 
    _date_re = re.compile(
 
689
    _date_regex = lazy_regex.lazy_compile(
618
690
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
619
691
            r'(,|T)?\s*'
620
692
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
638
710
        elif self.spec.lower() == 'tomorrow':
639
711
            dt = today + datetime.timedelta(days=1)
640
712
        else:
641
 
            m = self._date_re.match(self.spec)
 
713
            m = self._date_regex.match(self.spec)
642
714
            if not m or (not m.group('date') and not m.group('time')):
643
715
                raise errors.InvalidRevisionSpec(self.user_spec,
644
716
                                                 branch, 'invalid date')
761
833
      branch:/path/to/branch
762
834
    """
763
835
    prefix = 'branch:'
 
836
    dwim_catchable_exceptions = (errors.NotBranchError,)
764
837
 
765
838
    def _match_on(self, branch, revs):
766
839
        from bzrlib.branch import Branch
768
841
        revision_b = other_branch.last_revision()
769
842
        if revision_b in (None, revision.NULL_REVISION):
770
843
            raise errors.NoCommits(other_branch)
771
 
        # pull in the remote revisions so we can diff
772
 
        branch.fetch(other_branch, revision_b)
 
844
        if branch is None:
 
845
            branch = other_branch
 
846
        else:
 
847
            try:
 
848
                # pull in the remote revisions so we can diff
 
849
                branch.fetch(other_branch, revision_b)
 
850
            except errors.ReadOnlyError:
 
851
                branch = other_branch
773
852
        try:
774
853
            revno = branch.revision_id_to_revno(revision_b)
775
854
        except errors.NoSuchRevision:
795
874
            raise errors.NoCommits(other_branch)
796
875
        return other_branch.repository.revision_tree(last_revision)
797
876
 
 
877
    def needs_branch(self):
 
878
        return False
 
879
 
 
880
    def get_branch(self):
 
881
        return self.spec
 
882
 
798
883
 
799
884
 
800
885
class RevisionSpec_submit(RevisionSpec_ancestor):
826
911
            location_type = 'parent branch'
827
912
        if submit_location is None:
828
913
            raise errors.NoSubmitBranch(branch)
829
 
        trace.note('Using %s %s', location_type, submit_location)
 
914
        trace.note(gettext('Using {0} {1}').format(location_type,
 
915
                                                        submit_location))
830
916
        return submit_location
831
917
 
832
918
    def _match_on(self, branch, revs):
839
925
            self._get_submit_location(context_branch))
840
926
 
841
927
 
 
928
class RevisionSpec_annotate(RevisionIDSpec):
 
929
 
 
930
    prefix = 'annotate:'
 
931
 
 
932
    help_txt = """Select the revision that last modified the specified line.
 
933
 
 
934
    Select the revision that last modified the specified line.  Line is
 
935
    specified as path:number.  Path is a relative path to the file.  Numbers
 
936
    start at 1, and are relative to the current version, not the last-
 
937
    committed version of the file.
 
938
    """
 
939
 
 
940
    def _raise_invalid(self, numstring, context_branch):
 
941
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
942
            'No such line: %s' % numstring)
 
943
 
 
944
    def _as_revision_id(self, context_branch):
 
945
        path, numstring = self.spec.rsplit(':', 1)
 
946
        try:
 
947
            index = int(numstring) - 1
 
948
        except ValueError:
 
949
            self._raise_invalid(numstring, context_branch)
 
950
        tree, file_path = workingtree.WorkingTree.open_containing(path)
 
951
        tree.lock_read()
 
952
        try:
 
953
            file_id = tree.path2id(file_path)
 
954
            if file_id is None:
 
955
                raise errors.InvalidRevisionSpec(self.user_spec,
 
956
                    context_branch, "File '%s' is not versioned." %
 
957
                    file_path)
 
958
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
 
959
        finally:
 
960
            tree.unlock()
 
961
        try:
 
962
            revision_id = revision_ids[index]
 
963
        except IndexError:
 
964
            self._raise_invalid(numstring, context_branch)
 
965
        if revision_id == revision.CURRENT_REVISION:
 
966
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
967
                'Line %s has not been committed.' % numstring)
 
968
        return revision_id
 
969
 
 
970
 
 
971
class RevisionSpec_mainline(RevisionIDSpec):
 
972
 
 
973
    help_txt = """Select mainline revision that merged the specified revision.
 
974
 
 
975
    Select the revision that merged the specified revision into mainline.
 
976
    """
 
977
 
 
978
    prefix = 'mainline:'
 
979
 
 
980
    def _as_revision_id(self, context_branch):
 
981
        revspec = RevisionSpec.from_string(self.spec)
 
982
        if revspec.get_branch() is None:
 
983
            spec_branch = context_branch
 
984
        else:
 
985
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
 
986
        revision_id = revspec.as_revision_id(spec_branch)
 
987
        graph = context_branch.repository.get_graph()
 
988
        result = graph.find_lefthand_merger(revision_id,
 
989
                                            context_branch.last_revision())
 
990
        if result is None:
 
991
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
992
        return result
 
993
 
 
994
 
 
995
# The order in which we want to DWIM a revision spec without any prefix.
 
996
# revno is always tried first and isn't listed here, this is used by
 
997
# RevisionSpec_dwim._match_on
 
998
dwim_revspecs = symbol_versioning.deprecated_list(
 
999
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])
 
1000
 
 
1001
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
 
1002
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
 
1003
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
 
1004
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
 
1005
 
842
1006
revspec_registry = registry.Registry()
843
1007
def _register_revspec(revspec):
844
1008
    revspec_registry.register(revspec.prefix, revspec)
852
1016
_register_revspec(RevisionSpec_ancestor)
853
1017
_register_revspec(RevisionSpec_branch)
854
1018
_register_revspec(RevisionSpec_submit)
855
 
 
856
 
SPEC_TYPES = symbol_versioning.deprecated_list(
857
 
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])
 
1019
_register_revspec(RevisionSpec_annotate)
 
1020
_register_revspec(RevisionSpec_mainline)