~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Packman
  • Date: 2011-12-23 19:38:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6405.
  • Revision ID: martin.packman@canonical.com-20111223193822-hesheea4o8aqwexv
Accept and document passing the medium rather than transport for smart connections

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