~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-03-28 06:58:22 UTC
  • mfrom: (2379.2.3 hpss-chroot)
  • Revision ID: pqm@pqm.ubuntu.com-20070328065822-999550a858a3ced3
(robertc) Fix chroot urls to not expose the url of the transport they are protecting, allowing regular url operations to work on them. (Robert Collins, Andrew Bennetts)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
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., 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(), """
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
22
18
import bisect
23
19
import datetime
 
20
import re
24
21
 
25
22
from bzrlib import (
26
 
    branch as _mod_branch,
 
23
    errors,
27
24
    osutils,
28
25
    revision,
29
26
    symbol_versioning,
30
 
    workingtree,
31
 
    )
32
 
from bzrlib.i18n import gettext
33
 
""")
34
 
 
35
 
from bzrlib import (
36
 
    errors,
37
 
    lazy_regex,
38
 
    registry,
39
27
    trace,
 
28
    tsort,
40
29
    )
41
30
 
42
31
 
 
32
_marker = []
 
33
 
 
34
 
43
35
class RevisionInfo(object):
44
36
    """The results of applying a revision specification to a branch."""
45
37
 
57
49
    or treat the result as a tuple.
58
50
    """
59
51
 
60
 
    def __init__(self, branch, revno=None, rev_id=None):
 
52
    def __init__(self, branch, revno, rev_id=_marker):
61
53
        self.branch = branch
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:
 
54
        self.revno = revno
 
55
        if rev_id is _marker:
66
56
            # allow caller to be lazy
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
 
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
78
63
 
79
64
    def __nonzero__(self):
 
65
        # first the easy ones...
80
66
        if self.rev_id is None:
81
67
            return False
 
68
        if self.revno is not None:
 
69
            return True
82
70
        # TODO: otherwise, it should depend on how I was built -
83
71
        # if it's in_history(branch), then check revision_history(),
84
72
        # if it's in_store(branch), do the check below
107
95
            self.revno, self.rev_id, self.branch)
108
96
 
109
97
    @staticmethod
110
 
    def from_revision_id(branch, revision_id, revs=symbol_versioning.DEPRECATED_PARAMETER):
 
98
    def from_revision_id(branch, revision_id, revs):
111
99
        """Construct a RevisionInfo given just the id.
112
100
 
113
101
        Use this if you don't know or care what the revno is.
114
102
        """
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)
 
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
121
114
 
122
115
 
123
116
class RevisionSpec(object):
125
118
 
126
119
    help_txt = """A parsed revision specification.
127
120
 
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.
 
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.
132
125
 
133
126
    Revision specs are an UI element, and they have been moved out
134
127
    of the branch class to leave "back-end" classes unaware of such
140
133
    """
141
134
 
142
135
    prefix = None
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
 
    """
 
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)
153
147
 
154
148
    @staticmethod
155
149
    def from_string(spec):
164
158
 
165
159
        if spec is None:
166
160
            return RevisionSpec(None, _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)
 
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)
173
170
        else:
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)
 
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)
177
182
 
178
183
    def __init__(self, spec, _internal=False):
179
184
        """Create a RevisionSpec referring to the Null revision.
183
188
            called directly. Only from RevisionSpec.from_string()
184
189
        """
185
190
        if not _internal:
 
191
            # XXX: Update this after 0.10 is released
186
192
            symbol_versioning.warn('Creating a RevisionSpec directly has'
187
193
                                   ' been deprecated in version 0.11. Use'
188
194
                                   ' RevisionSpec.from_string()'
195
201
 
196
202
    def _match_on(self, branch, revs):
197
203
        trace.mutter('Returning RevisionSpec._match_on: None')
198
 
        return RevisionInfo(branch, None, None)
 
204
        return RevisionInfo(branch, 0, None)
199
205
 
200
206
    def _match_on_and_check(self, branch, revs):
201
207
        info = self._match_on(branch, revs)
202
208
        if info:
203
209
            return info
204
 
        elif info == (None, None):
205
 
            # special case - nothing supplied
 
210
        elif info == (0, None):
 
211
            # special case - the empty tree
206
212
            return info
207
213
        elif self.prefix:
208
214
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
211
217
 
212
218
    def in_history(self, branch):
213
219
        if branch:
214
 
            if self.wants_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()
227
 
            else:
228
 
                revs = None
 
220
            revs = branch.revision_history()
229
221
        else:
230
222
            # this should never trigger.
231
223
            # TODO: make it a deprecated code path. RBC 20060928
241
233
    # will do what you expect.
242
234
    in_store = in_history
243
235
    in_branch = in_store
244
 
 
245
 
    def as_revision_id(self, context_branch):
246
 
        """Return just the revision_id for this revisions spec.
247
 
 
248
 
        Some revision specs require a context_branch to be able to determine
249
 
        their value. Not all specs will make use of it.
250
 
        """
251
 
        return self._as_revision_id(context_branch)
252
 
 
253
 
    def _as_revision_id(self, context_branch):
254
 
        """Implementation of as_revision_id()
255
 
 
256
 
        Classes should override this function to provide appropriate
257
 
        functionality. The default is to just call '.in_history().rev_id'
258
 
        """
259
 
        return self.in_history(context_branch).rev_id
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
 
 
 
236
        
280
237
    def __repr__(self):
281
238
        # this is mostly for helping with testing
282
239
        return '<%s %s>' % (self.__class__.__name__,
283
240
                              self.user_spec)
284
 
 
 
241
    
285
242
    def needs_branch(self):
286
243
        """Whether this revision spec needs a branch.
287
244
 
291
248
 
292
249
    def get_branch(self):
293
250
        """When the revision specifier contains a branch location, return it.
294
 
 
 
251
        
295
252
        Otherwise, return None.
296
253
        """
297
254
        return None
299
256
 
300
257
# private API
301
258
 
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
 
 
373
259
class RevisionSpec_revno(RevisionSpec):
374
260
    """Selects a revision using a number."""
375
261
 
376
262
    help_txt = """Selects a revision using a number.
377
263
 
378
264
    Use an integer to specify a revision in the history of the branch.
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.
383
 
    Examples::
384
 
 
385
 
      revno:1                   -> return the first revision of this 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
386
271
      revno:3:/path/to/branch   -> return the 3rd revision of
387
272
                                   the branch '/path/to/branch'
388
273
      revno:-1                  -> The last revision in a branch.
395
280
 
396
281
    def _match_on(self, branch, revs):
397
282
        """Lookup a revision by revision number"""
398
 
        branch, revno, revision_id = self._lookup(branch)
399
 
        return RevisionInfo(branch, revno, revision_id)
400
 
 
401
 
    def _lookup(self, branch):
402
283
        loc = self.spec.find(':')
403
284
        if loc == -1:
404
285
            revno_spec = self.spec
418
299
                dotted = False
419
300
            except ValueError:
420
301
                # dotted decimal. This arguably should not be here
421
 
                # but the from_string method is a little primitive
 
302
                # but the from_string method is a little primitive 
422
303
                # right now - RBC 20060928
423
304
                try:
424
305
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
428
309
                dotted = True
429
310
 
430
311
        if branch_spec:
431
 
            # the user has overriden the branch to look in.
432
 
            branch = _mod_branch.Branch.open(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()
433
320
 
434
321
        if dotted:
 
322
            branch.lock_read()
435
323
            try:
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)
 
324
                last_rev = branch.last_revision()
 
325
                merge_sorted_revisions = tsort.merge_sort(
 
326
                    branch.repository.get_revision_graph(last_rev),
 
327
                    last_rev,
 
328
                    generate_revno=True)
 
329
                def match(item):
 
330
                    return item[3] == match_revno
 
331
                revisions = filter(match, merge_sorted_revisions)
 
332
            finally:
 
333
                branch.unlock()
 
334
            if len(revisions) != 1:
 
335
                return RevisionInfo(branch, None, None)
440
336
            else:
441
337
                # there is no traditional 'revno' for dotted-decimal revnos.
442
 
                # so for API compatibility we return None.
443
 
                return branch, None, revision_id
 
338
                # so for  API compatability we return None.
 
339
                return RevisionInfo(branch, None, revisions[0][1])
444
340
        else:
445
 
            last_revno, last_revision_id = branch.last_revision_info()
446
341
            if revno < 0:
447
342
                # if get_rev_id supported negative revnos, there would not be a
448
343
                # need for this special case.
449
 
                if (-revno) >= last_revno:
 
344
                if (-revno) >= len(revs):
450
345
                    revno = 1
451
346
                else:
452
 
                    revno = last_revno + revno + 1
 
347
                    revno = len(revs) + revno + 1
453
348
            try:
454
 
                revision_id = branch.get_rev_id(revno)
 
349
                revision_id = branch.get_rev_id(revno, revs)
455
350
            except errors.NoSuchRevision:
456
351
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
457
 
        return branch, revno, revision_id
458
 
 
459
 
    def _as_revision_id(self, context_branch):
460
 
        # We would have the revno here, but we don't really care
461
 
        branch, revno, revision_id = self._lookup(context_branch)
462
 
        return revision_id
463
 
 
 
352
        return RevisionInfo(branch, revno, revision_id)
 
353
        
464
354
    def needs_branch(self):
465
355
        return self.spec.find(':') == -1
466
356
 
470
360
        else:
471
361
            return self.spec[self.spec.find(':')+1:]
472
362
 
473
 
# Old compatibility
 
363
# Old compatibility 
474
364
RevisionSpec_int = RevisionSpec_revno
475
365
 
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):
 
366
SPEC_TYPES.append(RevisionSpec_revno)
 
367
 
 
368
 
 
369
class RevisionSpec_revid(RevisionSpec):
485
370
    """Selects a revision using the revision id."""
486
371
 
487
372
    help_txt = """Selects a revision using the revision id.
488
373
 
489
374
    Supply a specific revision id, that can be used to specify any
490
 
    revision id in the ancestry of the branch.
 
375
    revision id in the ancestry of the branch. 
491
376
    Including merges, and pending merges.
492
 
    Examples::
493
 
 
 
377
    examples:
494
378
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
495
 
    """
496
 
 
 
379
    """    
497
380
    prefix = 'revid:'
498
381
 
499
 
    def _as_revision_id(self, context_branch):
 
382
    def _match_on(self, branch, revs):
500
383
        # self.spec comes straight from parsing the command line arguments,
501
384
        # so we expect it to be a Unicode string. Switch it to the internal
502
385
        # representation.
503
 
        return osutils.safe_revision_id(self.spec, warn=False)
 
386
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
387
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
504
388
 
 
389
SPEC_TYPES.append(RevisionSpec_revid)
505
390
 
506
391
 
507
392
class RevisionSpec_last(RevisionSpec):
511
396
 
512
397
    Supply a positive number to get the nth revision from the end.
513
398
    This is the same as supplying negative numbers to the 'revno:' spec.
514
 
    Examples::
515
 
 
 
399
    examples:
516
400
      last:1        -> return the last revision
517
401
      last:3        -> return the revision 2 before the end.
518
 
    """
 
402
    """    
519
403
 
520
404
    prefix = 'last:'
521
405
 
522
406
    def _match_on(self, branch, revs):
523
 
        revno, revision_id = self._revno_and_revision_id(branch)
524
 
        return RevisionInfo(branch, revno, revision_id)
525
 
 
526
 
    def _revno_and_revision_id(self, context_branch):
527
 
        last_revno, last_revision_id = context_branch.last_revision_info()
528
 
 
529
407
        if self.spec == '':
530
 
            if not last_revno:
531
 
                raise errors.NoCommits(context_branch)
532
 
            return last_revno, last_revision_id
 
408
            if not revs:
 
409
                raise errors.NoCommits(branch)
 
410
            return RevisionInfo(branch, len(revs), revs[-1])
533
411
 
534
412
        try:
535
413
            offset = int(self.spec)
536
414
        except ValueError, e:
537
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
 
415
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
538
416
 
539
417
        if offset <= 0:
540
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
418
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
541
419
                                             'you must supply a positive value')
542
 
 
543
 
        revno = last_revno - offset + 1
 
420
        revno = len(revs) - offset + 1
544
421
        try:
545
 
            revision_id = context_branch.get_rev_id(revno)
 
422
            revision_id = branch.get_rev_id(revno, revs)
546
423
        except errors.NoSuchRevision:
547
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
548
 
        return revno, revision_id
549
 
 
550
 
    def _as_revision_id(self, context_branch):
551
 
        # We compute the revno as part of the process, but we don't really care
552
 
        # about it.
553
 
        revno, revision_id = self._revno_and_revision_id(context_branch)
554
 
        return revision_id
555
 
 
 
424
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
425
        return RevisionInfo(branch, revno, revision_id)
 
426
 
 
427
SPEC_TYPES.append(RevisionSpec_last)
556
428
 
557
429
 
558
430
class RevisionSpec_before(RevisionSpec):
560
432
 
561
433
    help_txt = """Selects the parent of the revision specified.
562
434
 
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
 
 
 
435
    Supply any revision spec to return the parent of that revision.
567
436
    It is an error to request the parent of the null revision (before:0).
568
 
 
569
 
    Examples::
570
 
 
 
437
    This is mostly useful when inspecting revisions that are not in the
 
438
    revision history of a branch.
 
439
 
 
440
    examples:
571
441
      before:1913    -> Return the parent of revno 1913 (revno 1912)
572
442
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
573
443
                                            aaaa@bbbb-1234567890
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
 
444
      bzr diff -r before:revid:aaaa..revid:aaaa
 
445
            -> Find the changes between revision 'aaaa' and its parent.
 
446
               (what changes did 'aaaa' introduce)
578
447
    """
579
448
 
580
449
    prefix = 'before:'
581
 
 
 
450
    
582
451
    def _match_on(self, branch, revs):
583
452
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
584
453
        if r.revno == 0:
588
457
            # We need to use the repository history here
589
458
            rev = branch.repository.get_revision(r.rev_id)
590
459
            if not rev.parent_ids:
591
 
                revision_id = revision.NULL_REVISION
 
460
                revno = 0
 
461
                revision_id = None
592
462
            else:
593
463
                revision_id = rev.parent_ids[0]
594
 
            revno = None
 
464
                try:
 
465
                    revno = revs.index(revision_id) + 1
 
466
                except ValueError:
 
467
                    revno = None
595
468
        else:
596
469
            revno = r.revno - 1
597
470
            try:
601
474
                                                 branch)
602
475
        return RevisionInfo(branch, revno, revision_id)
603
476
 
604
 
    def _as_revision_id(self, context_branch):
605
 
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
606
 
        if base_revision_id == revision.NULL_REVISION:
607
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
608
 
                                         'cannot go before the null: revision')
609
 
        context_repo = context_branch.repository
610
 
        context_repo.lock_read()
611
 
        try:
612
 
            parent_map = context_repo.get_parent_map([base_revision_id])
613
 
        finally:
614
 
            context_repo.unlock()
615
 
        if base_revision_id not in parent_map:
616
 
            # Ghost, or unknown revision id
617
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
618
 
                'cannot find the matching revision')
619
 
        parents = parent_map[base_revision_id]
620
 
        if len(parents) < 1:
621
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
622
 
                'No parents for revision.')
623
 
        return parents[0]
624
 
 
 
477
SPEC_TYPES.append(RevisionSpec_before)
625
478
 
626
479
 
627
480
class RevisionSpec_tag(RevisionSpec):
633
486
    """
634
487
 
635
488
    prefix = 'tag:'
636
 
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
637
489
 
638
490
    def _match_on(self, branch, revs):
639
491
        # Can raise tags not supported, NoSuchTag, etc
640
492
        return RevisionInfo.from_revision_id(branch,
641
 
            branch.tags.lookup_tag(self.spec))
642
 
 
643
 
    def _as_revision_id(self, context_branch):
644
 
        return context_branch.tags.lookup_tag(self.spec)
645
 
 
 
493
            branch.tags.lookup_tag(self.spec),
 
494
            revs)
 
495
 
 
496
SPEC_TYPES.append(RevisionSpec_tag)
646
497
 
647
498
 
648
499
class _RevListToTimestamps(object):
649
500
    """This takes a list of revisions, and allows you to bisect by date"""
650
501
 
651
 
    __slots__ = ['branch']
 
502
    __slots__ = ['revs', 'branch']
652
503
 
653
 
    def __init__(self, branch):
 
504
    def __init__(self, revs, branch):
 
505
        self.revs = revs
654
506
        self.branch = branch
655
507
 
656
508
    def __getitem__(self, index):
657
509
        """Get the date of the index'd item"""
658
 
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
 
510
        r = self.branch.repository.get_revision(self.revs[index])
659
511
        # TODO: Handle timezone.
660
512
        return datetime.datetime.fromtimestamp(r.timestamp)
661
513
 
662
514
    def __len__(self):
663
 
        return self.branch.revno()
 
515
        return len(self.revs)
664
516
 
665
517
 
666
518
class RevisionSpec_date(RevisionSpec):
673
525
    Matches the first entry after a given date (either at midnight or
674
526
    at a specified time).
675
527
 
676
 
    One way to display all the changes since yesterday would be::
677
 
 
678
 
        bzr log -r date:yesterday..
679
 
 
680
 
    Examples::
681
 
 
 
528
    One way to display all the changes since yesterday would be:
 
529
        bzr log -r date:yesterday..-1
 
530
 
 
531
    examples:
682
532
      date:yesterday            -> select the first revision since yesterday
683
533
      date:2006-08-14,17:10:14  -> select the first revision after
684
534
                                   August 14th, 2006 at 5:10pm.
685
 
    """
 
535
    """    
686
536
    prefix = 'date:'
687
 
    _date_regex = lazy_regex.lazy_compile(
 
537
    _date_re = re.compile(
688
538
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
689
539
            r'(,|T)?\s*'
690
540
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
708
558
        elif self.spec.lower() == 'tomorrow':
709
559
            dt = today + datetime.timedelta(days=1)
710
560
        else:
711
 
            m = self._date_regex.match(self.spec)
 
561
            m = self._date_re.match(self.spec)
712
562
            if not m or (not m.group('date') and not m.group('time')):
713
563
                raise errors.InvalidRevisionSpec(self.user_spec,
714
564
                                                 branch, 'invalid date')
740
590
                    hour=hour, minute=minute, second=second)
741
591
        branch.lock_read()
742
592
        try:
743
 
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
 
593
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
744
594
        finally:
745
595
            branch.unlock()
746
 
        if rev == branch.revno():
747
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
748
 
        return RevisionInfo(branch, rev)
 
596
        if rev == len(revs):
 
597
            return RevisionInfo(branch, None)
 
598
        else:
 
599
            return RevisionInfo(branch, rev + 1)
749
600
 
 
601
SPEC_TYPES.append(RevisionSpec_date)
750
602
 
751
603
 
752
604
class RevisionSpec_ancestor(RevisionSpec):
764
616
    that your branch introduces, while excluding the changes that you
765
617
    have not merged from the remote branch.
766
618
 
767
 
    Examples::
768
 
 
 
619
    examples:
769
620
      ancestor:/path/to/branch
770
621
      $ bzr diff -r ancestor:../../mainline/branch
771
622
    """
775
626
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
776
627
        return self._find_revision_info(branch, self.spec)
777
628
 
778
 
    def _as_revision_id(self, context_branch):
779
 
        return self._find_revision_id(context_branch, self.spec)
780
 
 
781
629
    @staticmethod
782
630
    def _find_revision_info(branch, other_location):
783
 
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
784
 
                                                              other_location)
785
 
        return RevisionInfo(branch, None, revision_id)
786
 
 
787
 
    @staticmethod
788
 
    def _find_revision_id(branch, other_location):
789
631
        from bzrlib.branch import Branch
790
632
 
791
 
        branch.lock_read()
 
633
        other_branch = Branch.open(other_location)
 
634
        revision_a = branch.last_revision()
 
635
        revision_b = other_branch.last_revision()
 
636
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
 
637
            if r in (None, revision.NULL_REVISION):
 
638
                raise errors.NoCommits(b)
 
639
        revision_source = revision.MultipleRevisionSources(
 
640
                branch.repository, other_branch.repository)
 
641
        rev_id = revision.common_ancestor(revision_a, revision_b,
 
642
                                          revision_source)
792
643
        try:
793
 
            revision_a = revision.ensure_null(branch.last_revision())
794
 
            if revision_a == revision.NULL_REVISION:
795
 
                raise errors.NoCommits(branch)
796
 
            if other_location == '':
797
 
                other_location = branch.get_parent()
798
 
            other_branch = Branch.open(other_location)
799
 
            other_branch.lock_read()
800
 
            try:
801
 
                revision_b = revision.ensure_null(other_branch.last_revision())
802
 
                if revision_b == revision.NULL_REVISION:
803
 
                    raise errors.NoCommits(other_branch)
804
 
                graph = branch.repository.get_graph(other_branch.repository)
805
 
                rev_id = graph.find_unique_lca(revision_a, revision_b)
806
 
            finally:
807
 
                other_branch.unlock()
808
 
            if rev_id == revision.NULL_REVISION:
809
 
                raise errors.NoCommonAncestor(revision_a, revision_b)
810
 
            return rev_id
811
 
        finally:
812
 
            branch.unlock()
813
 
 
814
 
 
 
644
            revno = branch.revision_id_to_revno(rev_id)
 
645
        except errors.NoSuchRevision:
 
646
            revno = None
 
647
        return RevisionInfo(branch, revno, rev_id)
 
648
 
 
649
 
 
650
SPEC_TYPES.append(RevisionSpec_ancestor)
815
651
 
816
652
 
817
653
class RevisionSpec_branch(RevisionSpec):
821
657
 
822
658
    Supply the path to a branch to select its last revision.
823
659
 
824
 
    Examples::
825
 
 
 
660
    examples:
826
661
      branch:/path/to/branch
827
662
    """
828
663
    prefix = 'branch:'
829
 
    dwim_catchable_exceptions = (errors.NotBranchError,)
830
664
 
831
665
    def _match_on(self, branch, revs):
832
666
        from bzrlib.branch import Branch
834
668
        revision_b = other_branch.last_revision()
835
669
        if revision_b in (None, revision.NULL_REVISION):
836
670
            raise errors.NoCommits(other_branch)
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)
846
 
 
847
 
    def _as_revision_id(self, context_branch):
848
 
        from bzrlib.branch import Branch
849
 
        other_branch = Branch.open(self.spec)
850
 
        last_revision = other_branch.last_revision()
851
 
        last_revision = revision.ensure_null(last_revision)
852
 
        context_branch.fetch(other_branch, last_revision)
853
 
        if last_revision == revision.NULL_REVISION:
854
 
            raise errors.NoCommits(other_branch)
855
 
        return last_revision
856
 
 
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
 
 
 
671
        # pull in the remote revisions so we can diff
 
672
        branch.fetch(other_branch, revision_b)
 
673
        try:
 
674
            revno = branch.revision_id_to_revno(revision_b)
 
675
        except errors.NoSuchRevision:
 
676
            revno = None
 
677
        return RevisionInfo(branch, revno, revision_b)
 
678
        
 
679
SPEC_TYPES.append(RevisionSpec_branch)
872
680
 
873
681
 
874
682
class RevisionSpec_submit(RevisionSpec_ancestor):
878
686
 
879
687
    Diffing against this shows all the changes that were made in this branch,
880
688
    and is a good predictor of what merge will do.  The submit branch is
881
 
    used by the bundle and merge directive commands.  If no submit branch
 
689
    used by the bundle and merge directive comands.  If no submit branch
882
690
    is specified, the parent branch is used instead.
883
691
 
884
692
    The common ancestor is the last revision that existed in both
885
693
    branches. Usually this is the branch point, but it could also be
886
694
    a revision that was merged.
887
695
 
888
 
    Examples::
889
 
 
 
696
    examples:
890
697
      $ bzr diff -r submit:
891
698
    """
892
699
 
893
700
    prefix = 'submit:'
894
701
 
895
 
    def _get_submit_location(self, branch):
 
702
    def _match_on(self, branch, revs):
 
703
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
896
704
        submit_location = branch.get_submit_branch()
897
705
        location_type = 'submit branch'
898
706
        if submit_location is None:
900
708
            location_type = 'parent branch'
901
709
        if submit_location is None:
902
710
            raise errors.NoSubmitBranch(branch)
903
 
        trace.note(gettext('Using {0} {1}').format(location_type,
904
 
                                                        submit_location))
905
 
        return submit_location
906
 
 
907
 
    def _match_on(self, branch, revs):
908
 
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
909
 
        return self._find_revision_info(branch,
910
 
            self._get_submit_location(branch))
911
 
 
912
 
    def _as_revision_id(self, context_branch):
913
 
        return self._find_revision_id(context_branch,
914
 
            self._get_submit_location(context_branch))
915
 
 
916
 
 
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)
 
711
        trace.note('Using %s %s', location_type, submit_location)
 
712
        return self._find_revision_info(branch, submit_location)
 
713
 
 
714
 
 
715
SPEC_TYPES.append(RevisionSpec_submit)