~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Patch Queue Manager
  • Date: 2016-04-21 04:10:52 UTC
  • mfrom: (6616.1.1 fix-en-user-guide)
  • Revision ID: pqm@pqm.ubuntu.com-20160421041052-clcye7ns1qcl2n7w
(richard-wilbur) Ensure build of English use guide always uses English text
 even when user's locale specifies a different language. (Jelmer Vernooij)

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
from __future__ import absolute_import
 
18
 
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
18
22
import bisect
19
23
import datetime
20
 
import re
21
24
 
22
25
from bzrlib import (
23
 
    errors,
 
26
    branch as _mod_branch,
24
27
    osutils,
25
28
    revision,
26
29
    symbol_versioning,
 
30
    workingtree,
 
31
    )
 
32
from bzrlib.i18n import gettext
 
33
""")
 
34
 
 
35
from bzrlib import (
 
36
    errors,
 
37
    lazy_regex,
 
38
    registry,
27
39
    trace,
28
 
    tsort,
29
40
    )
30
41
 
31
42
 
32
 
_marker = []
33
 
 
34
 
 
35
43
class RevisionInfo(object):
36
44
    """The results of applying a revision specification to a branch."""
37
45
 
49
57
    or treat the result as a tuple.
50
58
    """
51
59
 
52
 
    def __init__(self, branch, revno, rev_id=_marker):
 
60
    def __init__(self, branch, revno=None, rev_id=None):
53
61
        self.branch = branch
54
 
        self.revno = revno
55
 
        if rev_id is _marker:
 
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:
56
66
            # allow caller to be lazy
57
 
            if self.revno is None:
58
 
                self.rev_id = None
59
 
            else:
60
 
                self.rev_id = branch.get_rev_id(self.revno)
61
 
        else:
62
 
            self.rev_id = rev_id
 
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
78
 
64
79
    def __nonzero__(self):
65
 
        # first the easy ones...
66
80
        if self.rev_id is None:
67
81
            return False
68
 
        if self.revno is not None:
69
 
            return True
70
82
        # TODO: otherwise, it should depend on how I was built -
71
83
        # if it's in_history(branch), then check revision_history(),
72
84
        # if it's in_store(branch), do the check below
95
107
            self.revno, self.rev_id, self.branch)
96
108
 
97
109
    @staticmethod
98
 
    def from_revision_id(branch, revision_id, revs):
 
110
    def from_revision_id(branch, revision_id, revs=symbol_versioning.DEPRECATED_PARAMETER):
99
111
        """Construct a RevisionInfo given just the id.
100
112
 
101
113
        Use this if you don't know or care what the revno is.
102
114
        """
103
 
        if revision_id == revision.NULL_REVISION:
104
 
            return RevisionInfo(branch, 0, revision_id)
105
 
        try:
106
 
            revno = revs.index(revision_id) + 1
107
 
        except ValueError:
108
 
            revno = None
109
 
        return RevisionInfo(branch, revno, revision_id)
110
 
 
111
 
 
112
 
# classes in this list should have a "prefix" attribute, against which
113
 
# string specs are matched
114
 
SPEC_TYPES = []
115
 
_revno_regex = None
 
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)
116
121
 
117
122
 
118
123
class RevisionSpec(object):
120
125
 
121
126
    help_txt = """A parsed revision specification.
122
127
 
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
    A revision specification is a string, which may be unambiguous about
 
129
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
 
130
    or it may have no prefix, in which case it's tried against several
 
131
    specifier types in sequence to determine what the user meant.
127
132
 
128
133
    Revision specs are an UI element, and they have been moved out
129
134
    of the branch class to leave "back-end" classes unaware of such
135
140
    """
136
141
 
137
142
    prefix = None
138
 
    wants_revision_history = True
139
 
 
140
 
    def __new__(cls, spec, _internal=False):
141
 
        if _internal:
142
 
            return object.__new__(cls, spec, _internal=_internal)
143
 
 
144
 
        symbol_versioning.warn('Creating a RevisionSpec directly has'
145
 
                               ' been deprecated in version 0.11. Use'
146
 
                               ' RevisionSpec.from_string()'
147
 
                               ' instead.',
148
 
                               DeprecationWarning, stacklevel=2)
149
 
        return RevisionSpec.from_string(spec)
 
143
    # wants_revision_history has been deprecated in 2.5.
 
144
    wants_revision_history = False
 
145
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
 
146
    """Exceptions that RevisionSpec_dwim._match_on will catch.
 
147
 
 
148
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
 
149
    invalid revspec and raises some exception. The exceptions mentioned here
 
150
    will not be reported to the user but simply ignored without stopping the
 
151
    dwim processing.
 
152
    """
150
153
 
151
154
    @staticmethod
152
155
    def from_string(spec):
161
164
 
162
165
        if spec is None:
163
166
            return RevisionSpec(None, _internal=True)
164
 
        for spectype in SPEC_TYPES:
165
 
            if spec.startswith(spectype.prefix):
166
 
                trace.mutter('Returning RevisionSpec %s for %s',
167
 
                             spectype.__name__, spec)
168
 
                return spectype(spec, _internal=True)
 
167
        match = revspec_registry.get_prefix(spec)
 
168
        if match is not None:
 
169
            spectype, specsuffix = match
 
170
            trace.mutter('Returning RevisionSpec %s for %s',
 
171
                         spectype.__name__, spec)
 
172
            return spectype(spec, _internal=True)
169
173
        else:
170
 
            # RevisionSpec_revno is special cased, because it is the only
171
 
            # one that directly handles plain integers
172
 
            # TODO: This should not be special cased rather it should be
173
 
            # a method invocation on spectype.canparse()
174
 
            global _revno_regex
175
 
            if _revno_regex is None:
176
 
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
177
 
            if _revno_regex.match(spec) is not None:
178
 
                return RevisionSpec_revno(spec, _internal=True)
179
 
 
180
 
            raise errors.NoSuchRevisionSpec(spec)
 
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)
181
177
 
182
178
    def __init__(self, spec, _internal=False):
183
179
        """Create a RevisionSpec referring to the Null revision.
187
183
            called directly. Only from RevisionSpec.from_string()
188
184
        """
189
185
        if not _internal:
190
 
            # XXX: Update this after 0.10 is released
191
186
            symbol_versioning.warn('Creating a RevisionSpec directly has'
192
187
                                   ' been deprecated in version 0.11. Use'
193
188
                                   ' RevisionSpec.from_string()'
217
212
    def in_history(self, branch):
218
213
        if branch:
219
214
            if self.wants_revision_history:
220
 
                revs = branch.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()
221
227
            else:
222
228
                revs = None
223
229
        else:
252
258
        """
253
259
        return self.in_history(context_branch).rev_id
254
260
 
 
261
    def as_tree(self, context_branch):
 
262
        """Return the tree object for this revisions spec.
 
263
 
 
264
        Some revision specs require a context_branch to be able to determine
 
265
        the revision id and access the repository. Not all specs will make
 
266
        use of it.
 
267
        """
 
268
        return self._as_tree(context_branch)
 
269
 
 
270
    def _as_tree(self, context_branch):
 
271
        """Implementation of as_tree().
 
272
 
 
273
        Classes should override this function to provide appropriate
 
274
        functionality. The default is to just call '.as_revision_id()'
 
275
        and get the revision tree from context_branch's repository.
 
276
        """
 
277
        revision_id = self.as_revision_id(context_branch)
 
278
        return context_branch.repository.revision_tree(revision_id)
 
279
 
255
280
    def __repr__(self):
256
281
        # this is mostly for helping with testing
257
282
        return '<%s %s>' % (self.__class__.__name__,
258
283
                              self.user_spec)
259
 
    
 
284
 
260
285
    def needs_branch(self):
261
286
        """Whether this revision spec needs a branch.
262
287
 
266
291
 
267
292
    def get_branch(self):
268
293
        """When the revision specifier contains a branch location, return it.
269
 
        
 
294
 
270
295
        Otherwise, return None.
271
296
        """
272
297
        return None
274
299
 
275
300
# private API
276
301
 
 
302
class RevisionSpec_dwim(RevisionSpec):
 
303
    """Provides a DWIMish revision specifier lookup.
 
304
 
 
305
    Note that this does not go in the revspec_registry because by definition
 
306
    there is no prefix to identify it.  It's solely called from
 
307
    RevisionSpec.from_string() because the DWIMification happen when _match_on
 
308
    is called so the string describing the revision is kept here until needed.
 
309
    """
 
310
 
 
311
    help_txt = None
 
312
 
 
313
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
314
 
 
315
    # The revspecs to try
 
316
    _possible_revspecs = []
 
317
 
 
318
    def _try_spectype(self, rstype, branch):
 
319
        rs = rstype(self.spec, _internal=True)
 
320
        # Hit in_history to find out if it exists, or we need to try the
 
321
        # next type.
 
322
        return rs.in_history(branch)
 
323
 
 
324
    def _match_on(self, branch, revs):
 
325
        """Run the lookup and see what we can get."""
 
326
 
 
327
        # First, see if it's a revno
 
328
        if self._revno_regex.match(self.spec) is not None:
 
329
            try:
 
330
                return self._try_spectype(RevisionSpec_revno, branch)
 
331
            except RevisionSpec_revno.dwim_catchable_exceptions:
 
332
                pass
 
333
 
 
334
        # 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
        for rs_class in dwim_revspecs:
 
344
            try:
 
345
                return self._try_spectype(rs_class, branch)
 
346
            except rs_class.dwim_catchable_exceptions:
 
347
                pass
 
348
 
 
349
        # Well, I dunno what it is. Note that we don't try to keep track of the
 
350
        # first of last exception raised during the DWIM tries as none seems
 
351
        # really relevant.
 
352
        raise errors.InvalidRevisionSpec(self.spec, branch)
 
353
 
 
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
 
277
373
class RevisionSpec_revno(RevisionSpec):
278
374
    """Selects a revision using a number."""
279
375
 
280
376
    help_txt = """Selects a revision using a number.
281
377
 
282
378
    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.
 
379
    Optionally a branch can be specified.  A negative number will count
 
380
    from the end of the branch (-1 is the last revision, -2 the previous
 
381
    one). If the negative number is larger than the branch's history, the
 
382
    first revision is returned.
287
383
    Examples::
288
384
 
289
 
      revno:1                   -> return the first revision
 
385
      revno:1                   -> return the first revision of this branch
290
386
      revno:3:/path/to/branch   -> return the 3rd revision of
291
387
                                   the branch '/path/to/branch'
292
388
      revno:-1                  -> The last revision in a branch.
296
392
                                   your history is very long.
297
393
    """
298
394
    prefix = 'revno:'
299
 
    wants_revision_history = False
300
395
 
301
396
    def _match_on(self, branch, revs):
302
397
        """Lookup a revision by revision number"""
303
 
        branch, revno, revision_id = self._lookup(branch, revs)
 
398
        branch, revno, revision_id = self._lookup(branch)
304
399
        return RevisionInfo(branch, revno, revision_id)
305
400
 
306
 
    def _lookup(self, branch, revs_or_none):
 
401
    def _lookup(self, branch):
307
402
        loc = self.spec.find(':')
308
403
        if loc == -1:
309
404
            revno_spec = self.spec
323
418
                dotted = False
324
419
            except ValueError:
325
420
                # dotted decimal. This arguably should not be here
326
 
                # but the from_string method is a little primitive 
 
421
                # but the from_string method is a little primitive
327
422
                # right now - RBC 20060928
328
423
                try:
329
424
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
333
428
                dotted = True
334
429
 
335
430
        if branch_spec:
336
 
            # the user has override the branch to look in.
337
 
            # we need to refresh the revision_history map and
338
 
            # the branch object.
339
 
            from bzrlib.branch import Branch
340
 
            branch = Branch.open(branch_spec)
341
 
            revs_or_none = None
 
431
            # the user has overriden the branch to look in.
 
432
            branch = _mod_branch.Branch.open(branch_spec)
342
433
 
343
434
        if dotted:
344
 
            branch.lock_read()
345
435
            try:
346
 
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
347
 
                revisions = [revision_id for revision_id, revno
348
 
                             in revision_id_to_revno.iteritems()
349
 
                             if revno == match_revno]
350
 
            finally:
351
 
                branch.unlock()
352
 
            if len(revisions) != 1:
353
 
                return branch, None, None
 
436
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
 
437
                    _cache_reverse=True)
 
438
            except errors.NoSuchRevision:
 
439
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
354
440
            else:
355
441
                # there is no traditional 'revno' for dotted-decimal revnos.
356
 
                # so for  API compatability we return None.
357
 
                return branch, None, revisions[0]
 
442
                # so for API compatibility we return None.
 
443
                return branch, None, revision_id
358
444
        else:
359
445
            last_revno, last_revision_id = branch.last_revision_info()
360
446
            if revno < 0:
365
451
                else:
366
452
                    revno = last_revno + revno + 1
367
453
            try:
368
 
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
454
                revision_id = branch.get_rev_id(revno)
369
455
            except errors.NoSuchRevision:
370
456
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
371
457
        return branch, revno, revision_id
372
458
 
373
459
    def _as_revision_id(self, context_branch):
374
460
        # We would have the revno here, but we don't really care
375
 
        branch, revno, revision_id = self._lookup(context_branch, None)
 
461
        branch, revno, revision_id = self._lookup(context_branch)
376
462
        return revision_id
377
463
 
378
464
    def needs_branch(self):
384
470
        else:
385
471
            return self.spec[self.spec.find(':')+1:]
386
472
 
387
 
# Old compatibility 
 
473
# Old compatibility
388
474
RevisionSpec_int = RevisionSpec_revno
389
475
 
390
 
SPEC_TYPES.append(RevisionSpec_revno)
391
 
 
392
 
 
393
 
class RevisionSpec_revid(RevisionSpec):
 
476
 
 
477
class RevisionIDSpec(RevisionSpec):
 
478
 
 
479
    def _match_on(self, branch, revs):
 
480
        revision_id = self.as_revision_id(branch)
 
481
        return RevisionInfo.from_revision_id(branch, revision_id)
 
482
 
 
483
 
 
484
class RevisionSpec_revid(RevisionIDSpec):
394
485
    """Selects a revision using the revision id."""
395
486
 
396
487
    help_txt = """Selects a revision using the revision id.
397
488
 
398
489
    Supply a specific revision id, that can be used to specify any
399
 
    revision id in the ancestry of the branch. 
 
490
    revision id in the ancestry of the branch.
400
491
    Including merges, and pending merges.
401
492
    Examples::
402
493
 
405
496
 
406
497
    prefix = 'revid:'
407
498
 
408
 
    def _match_on(self, branch, revs):
 
499
    def _as_revision_id(self, context_branch):
409
500
        # self.spec comes straight from parsing the command line arguments,
410
501
        # so we expect it to be a Unicode string. Switch it to the internal
411
502
        # representation.
412
 
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
413
 
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
414
 
 
415
 
    def _as_revision_id(self, context_branch):
416
503
        return osutils.safe_revision_id(self.spec, warn=False)
417
504
 
418
 
SPEC_TYPES.append(RevisionSpec_revid)
419
505
 
420
506
 
421
507
class RevisionSpec_last(RevisionSpec):
434
520
    prefix = 'last:'
435
521
 
436
522
    def _match_on(self, branch, revs):
437
 
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
523
        revno, revision_id = self._revno_and_revision_id(branch)
438
524
        return RevisionInfo(branch, revno, revision_id)
439
525
 
440
 
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
526
    def _revno_and_revision_id(self, context_branch):
441
527
        last_revno, last_revision_id = context_branch.last_revision_info()
442
528
 
443
529
        if self.spec == '':
456
542
 
457
543
        revno = last_revno - offset + 1
458
544
        try:
459
 
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
 
545
            revision_id = context_branch.get_rev_id(revno)
460
546
        except errors.NoSuchRevision:
461
547
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
462
548
        return revno, revision_id
464
550
    def _as_revision_id(self, context_branch):
465
551
        # We compute the revno as part of the process, but we don't really care
466
552
        # about it.
467
 
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
553
        revno, revision_id = self._revno_and_revision_id(context_branch)
468
554
        return revision_id
469
555
 
470
 
SPEC_TYPES.append(RevisionSpec_last)
471
556
 
472
557
 
473
558
class RevisionSpec_before(RevisionSpec):
475
560
 
476
561
    help_txt = """Selects the parent of the revision specified.
477
562
 
478
 
    Supply any revision spec to return the parent of that revision.
 
563
    Supply any revision spec to return the parent of that revision.  This is
 
564
    mostly useful when inspecting revisions that are not in the revision history
 
565
    of a branch.
 
566
 
479
567
    It is an error to request the parent of the null revision (before:0).
480
 
    This is mostly useful when inspecting revisions that are not in the
481
 
    revision history of a branch.
482
568
 
483
569
    Examples::
484
570
 
485
571
      before:1913    -> Return the parent of revno 1913 (revno 1912)
486
572
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
487
573
                                            aaaa@bbbb-1234567890
488
 
      bzr diff -r before:revid:aaaa..revid:aaaa
489
 
            -> Find the changes between revision 'aaaa' and its parent.
490
 
               (what changes did 'aaaa' introduce)
 
574
      bzr diff -r before:1913..1913
 
575
            -> Find the changes between revision 1913 and its parent (1912).
 
576
               (What changes did revision 1913 introduce).
 
577
               This is equivalent to:  bzr diff -c 1913
491
578
    """
492
579
 
493
580
    prefix = 'before:'
494
 
    
 
581
 
495
582
    def _match_on(self, branch, revs):
496
583
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
497
584
        if r.revno == 0:
501
588
            # We need to use the repository history here
502
589
            rev = branch.repository.get_revision(r.rev_id)
503
590
            if not rev.parent_ids:
504
 
                revno = 0
505
591
                revision_id = revision.NULL_REVISION
506
592
            else:
507
593
                revision_id = rev.parent_ids[0]
508
 
                try:
509
 
                    revno = revs.index(revision_id) + 1
510
 
                except ValueError:
511
 
                    revno = None
 
594
            revno = None
512
595
        else:
513
596
            revno = r.revno - 1
514
597
            try:
519
602
        return RevisionInfo(branch, revno, revision_id)
520
603
 
521
604
    def _as_revision_id(self, context_branch):
522
 
        base_revspec = RevisionSpec.from_string(self.spec)
523
 
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
605
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
524
606
        if base_revision_id == revision.NULL_REVISION:
525
607
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
526
608
                                         'cannot go before the null: revision')
540
622
                'No parents for revision.')
541
623
        return parents[0]
542
624
 
543
 
SPEC_TYPES.append(RevisionSpec_before)
544
625
 
545
626
 
546
627
class RevisionSpec_tag(RevisionSpec):
552
633
    """
553
634
 
554
635
    prefix = 'tag:'
 
636
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
555
637
 
556
638
    def _match_on(self, branch, revs):
557
639
        # Can raise tags not supported, NoSuchTag, etc
558
640
        return RevisionInfo.from_revision_id(branch,
559
 
            branch.tags.lookup_tag(self.spec),
560
 
            revs)
 
641
            branch.tags.lookup_tag(self.spec))
561
642
 
562
643
    def _as_revision_id(self, context_branch):
563
644
        return context_branch.tags.lookup_tag(self.spec)
564
645
 
565
 
SPEC_TYPES.append(RevisionSpec_tag)
566
646
 
567
647
 
568
648
class _RevListToTimestamps(object):
569
649
    """This takes a list of revisions, and allows you to bisect by date"""
570
650
 
571
 
    __slots__ = ['revs', 'branch']
 
651
    __slots__ = ['branch']
572
652
 
573
 
    def __init__(self, revs, branch):
574
 
        self.revs = revs
 
653
    def __init__(self, branch):
575
654
        self.branch = branch
576
655
 
577
656
    def __getitem__(self, index):
578
657
        """Get the date of the index'd item"""
579
 
        r = self.branch.repository.get_revision(self.revs[index])
 
658
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
580
659
        # TODO: Handle timezone.
581
660
        return datetime.datetime.fromtimestamp(r.timestamp)
582
661
 
583
662
    def __len__(self):
584
 
        return len(self.revs)
 
663
        return self.branch.revno()
585
664
 
586
665
 
587
666
class RevisionSpec_date(RevisionSpec):
603
682
      date:yesterday            -> select the first revision since yesterday
604
683
      date:2006-08-14,17:10:14  -> select the first revision after
605
684
                                   August 14th, 2006 at 5:10pm.
606
 
    """    
 
685
    """
607
686
    prefix = 'date:'
608
 
    _date_re = re.compile(
 
687
    _date_regex = lazy_regex.lazy_compile(
609
688
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
610
689
            r'(,|T)?\s*'
611
690
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
629
708
        elif self.spec.lower() == 'tomorrow':
630
709
            dt = today + datetime.timedelta(days=1)
631
710
        else:
632
 
            m = self._date_re.match(self.spec)
 
711
            m = self._date_regex.match(self.spec)
633
712
            if not m or (not m.group('date') and not m.group('time')):
634
713
                raise errors.InvalidRevisionSpec(self.user_spec,
635
714
                                                 branch, 'invalid date')
661
740
                    hour=hour, minute=minute, second=second)
662
741
        branch.lock_read()
663
742
        try:
664
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
743
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
665
744
        finally:
666
745
            branch.unlock()
667
 
        if rev == len(revs):
 
746
        if rev == branch.revno():
668
747
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
669
 
        else:
670
 
            return RevisionInfo(branch, rev + 1)
 
748
        return RevisionInfo(branch, rev)
671
749
 
672
 
SPEC_TYPES.append(RevisionSpec_date)
673
750
 
674
751
 
675
752
class RevisionSpec_ancestor(RevisionSpec):
705
782
    def _find_revision_info(branch, other_location):
706
783
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
707
784
                                                              other_location)
708
 
        try:
709
 
            revno = branch.revision_id_to_revno(revision_id)
710
 
        except errors.NoSuchRevision:
711
 
            revno = None
712
 
        return RevisionInfo(branch, revno, revision_id)
 
785
        return RevisionInfo(branch, None, revision_id)
713
786
 
714
787
    @staticmethod
715
788
    def _find_revision_id(branch, other_location):
720
793
            revision_a = revision.ensure_null(branch.last_revision())
721
794
            if revision_a == revision.NULL_REVISION:
722
795
                raise errors.NoCommits(branch)
 
796
            if other_location == '':
 
797
                other_location = branch.get_parent()
723
798
            other_branch = Branch.open(other_location)
724
799
            other_branch.lock_read()
725
800
            try:
737
812
            branch.unlock()
738
813
 
739
814
 
740
 
SPEC_TYPES.append(RevisionSpec_ancestor)
741
815
 
742
816
 
743
817
class RevisionSpec_branch(RevisionSpec):
752
826
      branch:/path/to/branch
753
827
    """
754
828
    prefix = 'branch:'
 
829
    dwim_catchable_exceptions = (errors.NotBranchError,)
755
830
 
756
831
    def _match_on(self, branch, revs):
757
832
        from bzrlib.branch import Branch
759
834
        revision_b = other_branch.last_revision()
760
835
        if revision_b in (None, revision.NULL_REVISION):
761
836
            raise errors.NoCommits(other_branch)
762
 
        # pull in the remote revisions so we can diff
763
 
        branch.fetch(other_branch, revision_b)
764
 
        try:
765
 
            revno = branch.revision_id_to_revno(revision_b)
766
 
        except errors.NoSuchRevision:
767
 
            revno = None
768
 
        return RevisionInfo(branch, revno, revision_b)
 
837
        if branch is None:
 
838
            branch = other_branch
 
839
        else:
 
840
            try:
 
841
                # pull in the remote revisions so we can diff
 
842
                branch.fetch(other_branch, revision_b)
 
843
            except errors.ReadOnlyError:
 
844
                branch = other_branch
 
845
        return RevisionInfo(branch, None, revision_b)
769
846
 
770
847
    def _as_revision_id(self, context_branch):
771
848
        from bzrlib.branch import Branch
777
854
            raise errors.NoCommits(other_branch)
778
855
        return last_revision
779
856
 
780
 
SPEC_TYPES.append(RevisionSpec_branch)
 
857
    def _as_tree(self, context_branch):
 
858
        from bzrlib.branch import Branch
 
859
        other_branch = Branch.open(self.spec)
 
860
        last_revision = other_branch.last_revision()
 
861
        last_revision = revision.ensure_null(last_revision)
 
862
        if last_revision == revision.NULL_REVISION:
 
863
            raise errors.NoCommits(other_branch)
 
864
        return other_branch.repository.revision_tree(last_revision)
 
865
 
 
866
    def needs_branch(self):
 
867
        return False
 
868
 
 
869
    def get_branch(self):
 
870
        return self.spec
 
871
 
781
872
 
782
873
 
783
874
class RevisionSpec_submit(RevisionSpec_ancestor):
809
900
            location_type = 'parent branch'
810
901
        if submit_location is None:
811
902
            raise errors.NoSubmitBranch(branch)
812
 
        trace.note('Using %s %s', location_type, submit_location)
 
903
        trace.note(gettext('Using {0} {1}').format(location_type,
 
904
                                                        submit_location))
813
905
        return submit_location
814
906
 
815
907
    def _match_on(self, branch, revs):
822
914
            self._get_submit_location(context_branch))
823
915
 
824
916
 
825
 
SPEC_TYPES.append(RevisionSpec_submit)
 
917
class RevisionSpec_annotate(RevisionIDSpec):
 
918
 
 
919
    prefix = 'annotate:'
 
920
 
 
921
    help_txt = """Select the revision that last modified the specified line.
 
922
 
 
923
    Select the revision that last modified the specified line.  Line is
 
924
    specified as path:number.  Path is a relative path to the file.  Numbers
 
925
    start at 1, and are relative to the current version, not the last-
 
926
    committed version of the file.
 
927
    """
 
928
 
 
929
    def _raise_invalid(self, numstring, context_branch):
 
930
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
931
            'No such line: %s' % numstring)
 
932
 
 
933
    def _as_revision_id(self, context_branch):
 
934
        path, numstring = self.spec.rsplit(':', 1)
 
935
        try:
 
936
            index = int(numstring) - 1
 
937
        except ValueError:
 
938
            self._raise_invalid(numstring, context_branch)
 
939
        tree, file_path = workingtree.WorkingTree.open_containing(path)
 
940
        tree.lock_read()
 
941
        try:
 
942
            file_id = tree.path2id(file_path)
 
943
            if file_id is None:
 
944
                raise errors.InvalidRevisionSpec(self.user_spec,
 
945
                    context_branch, "File '%s' is not versioned." %
 
946
                    file_path)
 
947
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
 
948
        finally:
 
949
            tree.unlock()
 
950
        try:
 
951
            revision_id = revision_ids[index]
 
952
        except IndexError:
 
953
            self._raise_invalid(numstring, context_branch)
 
954
        if revision_id == revision.CURRENT_REVISION:
 
955
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
956
                'Line %s has not been committed.' % numstring)
 
957
        return revision_id
 
958
 
 
959
 
 
960
class RevisionSpec_mainline(RevisionIDSpec):
 
961
 
 
962
    help_txt = """Select mainline revision that merged the specified revision.
 
963
 
 
964
    Select the revision that merged the specified revision into mainline.
 
965
    """
 
966
 
 
967
    prefix = 'mainline:'
 
968
 
 
969
    def _as_revision_id(self, context_branch):
 
970
        revspec = RevisionSpec.from_string(self.spec)
 
971
        if revspec.get_branch() is None:
 
972
            spec_branch = context_branch
 
973
        else:
 
974
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
 
975
        revision_id = revspec.as_revision_id(spec_branch)
 
976
        graph = context_branch.repository.get_graph()
 
977
        result = graph.find_lefthand_merger(revision_id,
 
978
                                            context_branch.last_revision())
 
979
        if result is None:
 
980
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
981
        return result
 
982
 
 
983
 
 
984
# The order in which we want to DWIM a revision spec without any prefix.
 
985
# revno is always tried first and isn't listed here, this is used by
 
986
# RevisionSpec_dwim._match_on
 
987
dwim_revspecs = symbol_versioning.deprecated_list(
 
988
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])
 
989
 
 
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
 
 
995
revspec_registry = registry.Registry()
 
996
def _register_revspec(revspec):
 
997
    revspec_registry.register(revspec.prefix, revspec)
 
998
 
 
999
_register_revspec(RevisionSpec_revno)
 
1000
_register_revspec(RevisionSpec_revid)
 
1001
_register_revspec(RevisionSpec_last)
 
1002
_register_revspec(RevisionSpec_before)
 
1003
_register_revspec(RevisionSpec_tag)
 
1004
_register_revspec(RevisionSpec_date)
 
1005
_register_revspec(RevisionSpec_ancestor)
 
1006
_register_revspec(RevisionSpec_branch)
 
1007
_register_revspec(RevisionSpec_submit)
 
1008
_register_revspec(RevisionSpec_annotate)
 
1009
_register_revspec(RevisionSpec_mainline)