~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: 2008-04-16 17:28:09 UTC
  • mfrom: (3369.1.1 bug_213771)
  • Revision ID: pqm@pqm.ubuntu.com-20080416172809-mq3p3rm6q3vefyyz
(jam) Remove annoying mutter(), bug #213771

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
 
18
import bisect
18
19
import datetime
19
20
import re
20
 
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
 
21
 
 
22
from bzrlib import (
 
23
    errors,
 
24
    osutils,
 
25
    revision,
 
26
    symbol_versioning,
 
27
    trace,
 
28
    tsort,
 
29
    )
 
30
 
21
31
 
22
32
_marker = []
23
33
 
 
34
 
24
35
class RevisionInfo(object):
25
 
    """The results of applying a revision specification to a branch.
 
36
    """The results of applying a revision specification to a branch."""
 
37
 
 
38
    help_txt = """The results of applying a revision specification to a branch.
26
39
 
27
40
    An instance has two useful attributes: revno, and rev_id.
28
41
 
57
70
        # TODO: otherwise, it should depend on how I was built -
58
71
        # if it's in_history(branch), then check revision_history(),
59
72
        # if it's in_store(branch), do the check below
60
 
        return self.branch.revision_store.has_id(self.rev_id)
 
73
        return self.branch.repository.has_revision(self.rev_id)
61
74
 
62
75
    def __len__(self):
63
76
        return 2
68
81
        raise IndexError(index)
69
82
 
70
83
    def get(self):
71
 
        return self.branch.get_revision(self.rev_id)
 
84
        return self.branch.repository.get_revision(self.rev_id)
72
85
 
73
86
    def __eq__(self, other):
74
87
        if type(other) not in (tuple, list, type(self)):
81
94
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
82
95
            self.revno, self.rev_id, self.branch)
83
96
 
 
97
    @staticmethod
 
98
    def from_revision_id(branch, revision_id, revs):
 
99
        """Construct a RevisionInfo given just the id.
 
100
 
 
101
        Use this if you don't know or care what the revno is.
 
102
        """
 
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
 
84
112
# classes in this list should have a "prefix" attribute, against which
85
113
# string specs are matched
86
114
SPEC_TYPES = []
 
115
_revno_regex = None
 
116
 
87
117
 
88
118
class RevisionSpec(object):
89
 
    """A parsed revision specification.
 
119
    """A parsed revision specification."""
 
120
 
 
121
    help_txt = """A parsed revision specification.
90
122
 
91
123
    A revision specification can be an integer, in which case it is
92
124
    assumed to be a revno (though this will translate negative values
104
136
 
105
137
    prefix = None
106
138
 
107
 
    def __new__(cls, spec, foo=_marker):
108
 
        """Parse a revision specifier.
 
139
    def __new__(cls, spec, _internal=False):
 
140
        if _internal:
 
141
            return object.__new__(cls, spec, _internal=_internal)
 
142
 
 
143
        symbol_versioning.warn('Creating a RevisionSpec directly has'
 
144
                               ' been deprecated in version 0.11. Use'
 
145
                               ' RevisionSpec.from_string()'
 
146
                               ' instead.',
 
147
                               DeprecationWarning, stacklevel=2)
 
148
        return RevisionSpec.from_string(spec)
 
149
 
 
150
    @staticmethod
 
151
    def from_string(spec):
 
152
        """Parse a revision spec string into a RevisionSpec object.
 
153
 
 
154
        :param spec: A string specified by the user
 
155
        :return: A RevisionSpec object that understands how to parse the
 
156
            supplied notation.
109
157
        """
 
158
        if not isinstance(spec, (type(None), basestring)):
 
159
            raise TypeError('error')
 
160
 
110
161
        if spec is None:
111
 
            return object.__new__(RevisionSpec, spec)
112
 
 
113
 
        try:
114
 
            spec = int(spec)
115
 
        except ValueError:
116
 
            pass
117
 
 
118
 
        if isinstance(spec, int):
119
 
            return object.__new__(RevisionSpec_int, spec)
120
 
        elif isinstance(spec, basestring):
121
 
            for spectype in SPEC_TYPES:
122
 
                if spec.startswith(spectype.prefix):
123
 
                    return object.__new__(spectype, spec)
124
 
            else:
125
 
                raise BzrError('No namespace registered for string: %r' %
126
 
                               spec)
 
162
            return RevisionSpec(None, _internal=True)
 
163
 
 
164
        assert isinstance(spec, basestring), \
 
165
            "You should only supply strings not %s" % (type(spec),)
 
166
 
 
167
        for spectype in SPEC_TYPES:
 
168
            if spec.startswith(spectype.prefix):
 
169
                trace.mutter('Returning RevisionSpec %s for %s',
 
170
                             spectype.__name__, spec)
 
171
                return spectype(spec, _internal=True)
127
172
        else:
128
 
            raise TypeError('Unhandled revision type %s' % spec)
129
 
 
130
 
    def __init__(self, spec):
 
173
            # RevisionSpec_revno is special cased, because it is the only
 
174
            # one that directly handles plain integers
 
175
            # TODO: This should not be special cased rather it should be
 
176
            # a method invocation on spectype.canparse()
 
177
            global _revno_regex
 
178
            if _revno_regex is None:
 
179
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
180
            if _revno_regex.match(spec) is not None:
 
181
                return RevisionSpec_revno(spec, _internal=True)
 
182
 
 
183
            raise errors.NoSuchRevisionSpec(spec)
 
184
 
 
185
    def __init__(self, spec, _internal=False):
 
186
        """Create a RevisionSpec referring to the Null revision.
 
187
 
 
188
        :param spec: The original spec supplied by the user
 
189
        :param _internal: Used to ensure that RevisionSpec is not being
 
190
            called directly. Only from RevisionSpec.from_string()
 
191
        """
 
192
        if not _internal:
 
193
            # XXX: Update this after 0.10 is released
 
194
            symbol_versioning.warn('Creating a RevisionSpec directly has'
 
195
                                   ' been deprecated in version 0.11. Use'
 
196
                                   ' RevisionSpec.from_string()'
 
197
                                   ' instead.',
 
198
                                   DeprecationWarning, stacklevel=2)
 
199
        self.user_spec = spec
131
200
        if self.prefix and spec.startswith(self.prefix):
132
201
            spec = spec[len(self.prefix):]
133
202
        self.spec = spec
134
203
 
135
204
    def _match_on(self, branch, revs):
136
 
        return RevisionInfo(branch, 0, None)
 
205
        trace.mutter('Returning RevisionSpec._match_on: None')
 
206
        return RevisionInfo(branch, None, None)
137
207
 
138
208
    def _match_on_and_check(self, branch, revs):
139
209
        info = self._match_on(branch, revs)
140
210
        if info:
141
211
            return info
142
 
        elif info == (0, None):
143
 
            # special case - the empty tree
 
212
        elif info == (None, None):
 
213
            # special case - nothing supplied
144
214
            return info
145
215
        elif self.prefix:
146
 
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
 
216
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
147
217
        else:
148
 
            raise NoSuchRevision(branch, str(self.spec))
 
218
            raise errors.InvalidRevisionSpec(self.spec, branch)
149
219
 
150
220
    def in_history(self, branch):
151
 
        revs = branch.revision_history()
 
221
        if branch:
 
222
            revs = branch.revision_history()
 
223
        else:
 
224
            # this should never trigger.
 
225
            # TODO: make it a deprecated code path. RBC 20060928
 
226
            revs = None
152
227
        return self._match_on_and_check(branch, revs)
153
228
 
154
229
        # FIXME: in_history is somewhat broken,
160
235
    # will do what you expect.
161
236
    in_store = in_history
162
237
    in_branch = in_store
163
 
        
 
238
 
 
239
    def as_revision_id(self, context_branch):
 
240
        """Return just the revision_id for this revisions spec.
 
241
 
 
242
        Some revision specs require a context_branch to be able to determine
 
243
        their value. Not all specs will make use of it.
 
244
        """
 
245
        return self._as_revision_id(context_branch)
 
246
 
 
247
    def _as_revision_id(self, context_branch):
 
248
        """Implementation of as_revision_id()
 
249
 
 
250
        Classes should override this function to provide appropriate
 
251
        functionality. The default is to just call '.in_history().rev_id'
 
252
        """
 
253
        return self.in_history(context_branch).rev_id
 
254
 
164
255
    def __repr__(self):
165
256
        # this is mostly for helping with testing
166
 
        return '<%s %s%s>' % (self.__class__.__name__,
167
 
                              self.prefix or '',
168
 
                              self.spec)
 
257
        return '<%s %s>' % (self.__class__.__name__,
 
258
                              self.user_spec)
 
259
    
 
260
    def needs_branch(self):
 
261
        """Whether this revision spec needs a branch.
 
262
 
 
263
        Set this to False the branch argument of _match_on is not used.
 
264
        """
 
265
        return True
 
266
 
 
267
    def get_branch(self):
 
268
        """When the revision specifier contains a branch location, return it.
 
269
        
 
270
        Otherwise, return None.
 
271
        """
 
272
        return None
169
273
 
170
274
 
171
275
# private API
172
276
 
173
 
class RevisionSpec_int(RevisionSpec):
174
 
    """Spec is a number.  Special case."""
175
 
    def __init__(self, spec):
176
 
        self.spec = int(spec)
177
 
 
178
 
    def _match_on(self, branch, revs):
179
 
        if self.spec < 0:
180
 
            revno = len(revs) + self.spec + 1
181
 
        else:
182
 
            revno = self.spec
183
 
        rev_id = branch.get_rev_id(revno, revs)
184
 
        return RevisionInfo(branch, revno, rev_id)
185
 
 
186
 
 
187
277
class RevisionSpec_revno(RevisionSpec):
 
278
    """Selects a revision using a number."""
 
279
 
 
280
    help_txt = """Selects a revision using a number.
 
281
 
 
282
    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.
 
287
    Examples::
 
288
 
 
289
      revno:1                   -> return the first revision
 
290
      revno:3:/path/to/branch   -> return the 3rd revision of
 
291
                                   the branch '/path/to/branch'
 
292
      revno:-1                  -> The last revision in a branch.
 
293
      -2:http://other/branch    -> The second to last revision in the
 
294
                                   remote branch.
 
295
      -1000000                  -> Most likely the first revision, unless
 
296
                                   your history is very long.
 
297
    """
188
298
    prefix = 'revno:'
189
299
 
190
300
    def _match_on(self, branch, revs):
191
301
        """Lookup a revision by revision number"""
192
 
        try:
193
 
            return RevisionInfo(branch, int(self.spec))
194
 
        except ValueError:
195
 
            return RevisionInfo(branch, None)
 
302
        branch, revno, revision_id = self._lookup(branch, revs)
 
303
        return RevisionInfo(branch, revno, revision_id)
 
304
 
 
305
    def _lookup(self, branch, revs_or_none):
 
306
        loc = self.spec.find(':')
 
307
        if loc == -1:
 
308
            revno_spec = self.spec
 
309
            branch_spec = None
 
310
        else:
 
311
            revno_spec = self.spec[:loc]
 
312
            branch_spec = self.spec[loc+1:]
 
313
 
 
314
        if revno_spec == '':
 
315
            if not branch_spec:
 
316
                raise errors.InvalidRevisionSpec(self.user_spec,
 
317
                        branch, 'cannot have an empty revno and no branch')
 
318
            revno = None
 
319
        else:
 
320
            try:
 
321
                revno = int(revno_spec)
 
322
                dotted = False
 
323
            except ValueError:
 
324
                # dotted decimal. This arguably should not be here
 
325
                # but the from_string method is a little primitive 
 
326
                # right now - RBC 20060928
 
327
                try:
 
328
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
 
329
                except ValueError, e:
 
330
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
331
 
 
332
                dotted = True
 
333
 
 
334
        if branch_spec:
 
335
            # the user has override the branch to look in.
 
336
            # we need to refresh the revision_history map and
 
337
            # the branch object.
 
338
            from bzrlib.branch import Branch
 
339
            branch = Branch.open(branch_spec)
 
340
            revs_or_none = None
 
341
 
 
342
        if dotted:
 
343
            branch.lock_read()
 
344
            try:
 
345
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
 
346
                revisions = [revision_id for revision_id, revno
 
347
                             in revision_id_to_revno.iteritems()
 
348
                             if revno == match_revno]
 
349
            finally:
 
350
                branch.unlock()
 
351
            if len(revisions) != 1:
 
352
                return branch, None, None
 
353
            else:
 
354
                # there is no traditional 'revno' for dotted-decimal revnos.
 
355
                # so for  API compatability we return None.
 
356
                return branch, None, revisions[0]
 
357
        else:
 
358
            last_revno, last_revision_id = branch.last_revision_info()
 
359
            if revno < 0:
 
360
                # if get_rev_id supported negative revnos, there would not be a
 
361
                # need for this special case.
 
362
                if (-revno) >= last_revno:
 
363
                    revno = 1
 
364
                else:
 
365
                    revno = last_revno + revno + 1
 
366
            try:
 
367
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
368
            except errors.NoSuchRevision:
 
369
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
370
        return branch, revno, revision_id
 
371
 
 
372
    def _as_revision_id(self, context_branch):
 
373
        # We would have the revno here, but we don't really care
 
374
        branch, revno, revision_id = self._lookup(context_branch, None)
 
375
        return revision_id
 
376
 
 
377
    def needs_branch(self):
 
378
        return self.spec.find(':') == -1
 
379
 
 
380
    def get_branch(self):
 
381
        if self.spec.find(':') == -1:
 
382
            return None
 
383
        else:
 
384
            return self.spec[self.spec.find(':')+1:]
 
385
 
 
386
# Old compatibility 
 
387
RevisionSpec_int = RevisionSpec_revno
196
388
 
197
389
SPEC_TYPES.append(RevisionSpec_revno)
198
390
 
199
391
 
200
392
class RevisionSpec_revid(RevisionSpec):
 
393
    """Selects a revision using the revision id."""
 
394
 
 
395
    help_txt = """Selects a revision using the revision id.
 
396
 
 
397
    Supply a specific revision id, that can be used to specify any
 
398
    revision id in the ancestry of the branch. 
 
399
    Including merges, and pending merges.
 
400
    Examples::
 
401
 
 
402
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
 
403
    """
 
404
 
201
405
    prefix = 'revid:'
202
406
 
203
407
    def _match_on(self, branch, revs):
204
 
        try:
205
 
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
206
 
        except ValueError:
207
 
            return RevisionInfo(branch, None)
 
408
        # self.spec comes straight from parsing the command line arguments,
 
409
        # so we expect it to be a Unicode string. Switch it to the internal
 
410
        # representation.
 
411
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
412
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
413
 
 
414
    def _as_revision_id(self, context_branch):
 
415
        return osutils.safe_revision_id(self.spec, warn=False)
208
416
 
209
417
SPEC_TYPES.append(RevisionSpec_revid)
210
418
 
211
419
 
212
420
class RevisionSpec_last(RevisionSpec):
 
421
    """Selects the nth revision from the end."""
 
422
 
 
423
    help_txt = """Selects the nth revision from the end.
 
424
 
 
425
    Supply a positive number to get the nth revision from the end.
 
426
    This is the same as supplying negative numbers to the 'revno:' spec.
 
427
    Examples::
 
428
 
 
429
      last:1        -> return the last revision
 
430
      last:3        -> return the revision 2 before the end.
 
431
    """
213
432
 
214
433
    prefix = 'last:'
215
434
 
216
435
    def _match_on(self, branch, revs):
 
436
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
437
        return RevisionInfo(branch, revno, revision_id)
 
438
 
 
439
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
440
        last_revno, last_revision_id = context_branch.last_revision_info()
 
441
 
 
442
        if self.spec == '':
 
443
            if not last_revno:
 
444
                raise errors.NoCommits(context_branch)
 
445
            return last_revno, last_revision_id
 
446
 
217
447
        try:
218
448
            offset = int(self.spec)
219
 
        except ValueError:
220
 
            return RevisionInfo(branch, None)
221
 
        else:
222
 
            if offset <= 0:
223
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
224
 
            return RevisionInfo(branch, len(revs) - offset + 1)
 
449
        except ValueError, e:
 
450
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
 
451
 
 
452
        if offset <= 0:
 
453
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
454
                                             'you must supply a positive value')
 
455
 
 
456
        revno = last_revno - offset + 1
 
457
        try:
 
458
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
 
459
        except errors.NoSuchRevision:
 
460
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
461
        return revno, revision_id
 
462
 
 
463
    def _as_revision_id(self, context_branch):
 
464
        # We compute the revno as part of the process, but we don't really care
 
465
        # about it.
 
466
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
467
        return revision_id
225
468
 
226
469
SPEC_TYPES.append(RevisionSpec_last)
227
470
 
228
471
 
229
472
class RevisionSpec_before(RevisionSpec):
 
473
    """Selects the parent of the revision specified."""
 
474
 
 
475
    help_txt = """Selects the parent of the revision specified.
 
476
 
 
477
    Supply any revision spec to return the parent of that revision.
 
478
    It is an error to request the parent of the null revision (before:0).
 
479
    This is mostly useful when inspecting revisions that are not in the
 
480
    revision history of a branch.
 
481
 
 
482
    Examples::
 
483
 
 
484
      before:1913    -> Return the parent of revno 1913 (revno 1912)
 
485
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
 
486
                                            aaaa@bbbb-1234567890
 
487
      bzr diff -r before:revid:aaaa..revid:aaaa
 
488
            -> Find the changes between revision 'aaaa' and its parent.
 
489
               (what changes did 'aaaa' introduce)
 
490
    """
230
491
 
231
492
    prefix = 'before:'
232
493
    
233
494
    def _match_on(self, branch, revs):
234
 
        r = RevisionSpec(self.spec)._match_on(branch, revs)
235
 
        if (r.revno is None) or (r.revno == 0):
236
 
            return r
237
 
        return RevisionInfo(branch, r.revno - 1)
 
495
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
 
496
        if r.revno == 0:
 
497
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
498
                                         'cannot go before the null: revision')
 
499
        if r.revno is None:
 
500
            # We need to use the repository history here
 
501
            rev = branch.repository.get_revision(r.rev_id)
 
502
            if not rev.parent_ids:
 
503
                revno = 0
 
504
                revision_id = revision.NULL_REVISION
 
505
            else:
 
506
                revision_id = rev.parent_ids[0]
 
507
                try:
 
508
                    revno = revs.index(revision_id) + 1
 
509
                except ValueError:
 
510
                    revno = None
 
511
        else:
 
512
            revno = r.revno - 1
 
513
            try:
 
514
                revision_id = branch.get_rev_id(revno, revs)
 
515
            except errors.NoSuchRevision:
 
516
                raise errors.InvalidRevisionSpec(self.user_spec,
 
517
                                                 branch)
 
518
        return RevisionInfo(branch, revno, revision_id)
 
519
 
 
520
    def _as_revision_id(self, context_branch):
 
521
        base_revspec = RevisionSpec.from_string(self.spec)
 
522
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
523
        if base_revision_id == revision.NULL_REVISION:
 
524
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
525
                                         'cannot go before the null: revision')
 
526
        context_repo = context_branch.repository
 
527
        context_repo.lock_read()
 
528
        try:
 
529
            parent_map = context_repo.get_parent_map([base_revision_id])
 
530
        finally:
 
531
            context_repo.unlock()
 
532
        if base_revision_id not in parent_map:
 
533
            # Ghost, or unknown revision id
 
534
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
535
                'cannot find the matching revision')
 
536
        parents = parent_map[base_revision_id]
 
537
        if len(parents) < 1:
 
538
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
539
                'No parents for revision.')
 
540
        return parents[0]
238
541
 
239
542
SPEC_TYPES.append(RevisionSpec_before)
240
543
 
241
544
 
242
545
class RevisionSpec_tag(RevisionSpec):
 
546
    """Select a revision identified by tag name"""
 
547
 
 
548
    help_txt = """Selects a revision identified by a tag name.
 
549
 
 
550
    Tags are stored in the branch and created by the 'tag' command.
 
551
    """
 
552
 
243
553
    prefix = 'tag:'
244
554
 
245
555
    def _match_on(self, branch, revs):
246
 
        raise BzrError('tag: namespace registered, but not implemented.')
 
556
        # Can raise tags not supported, NoSuchTag, etc
 
557
        return RevisionInfo.from_revision_id(branch,
 
558
            branch.tags.lookup_tag(self.spec),
 
559
            revs)
 
560
 
 
561
    def _as_revision_id(self, context_branch):
 
562
        return context_branch.tags.lookup_tag(self.spec)
247
563
 
248
564
SPEC_TYPES.append(RevisionSpec_tag)
249
565
 
250
566
 
 
567
class _RevListToTimestamps(object):
 
568
    """This takes a list of revisions, and allows you to bisect by date"""
 
569
 
 
570
    __slots__ = ['revs', 'branch']
 
571
 
 
572
    def __init__(self, revs, branch):
 
573
        self.revs = revs
 
574
        self.branch = branch
 
575
 
 
576
    def __getitem__(self, index):
 
577
        """Get the date of the index'd item"""
 
578
        r = self.branch.repository.get_revision(self.revs[index])
 
579
        # TODO: Handle timezone.
 
580
        return datetime.datetime.fromtimestamp(r.timestamp)
 
581
 
 
582
    def __len__(self):
 
583
        return len(self.revs)
 
584
 
 
585
 
251
586
class RevisionSpec_date(RevisionSpec):
 
587
    """Selects a revision on the basis of a datestamp."""
 
588
 
 
589
    help_txt = """Selects a revision on the basis of a datestamp.
 
590
 
 
591
    Supply a datestamp to select the first revision that matches the date.
 
592
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
593
    Matches the first entry after a given date (either at midnight or
 
594
    at a specified time).
 
595
 
 
596
    One way to display all the changes since yesterday would be::
 
597
 
 
598
        bzr log -r date:yesterday..-1
 
599
 
 
600
    Examples::
 
601
 
 
602
      date:yesterday            -> select the first revision since yesterday
 
603
      date:2006-08-14,17:10:14  -> select the first revision after
 
604
                                   August 14th, 2006 at 5:10pm.
 
605
    """    
252
606
    prefix = 'date:'
253
607
    _date_re = re.compile(
254
608
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
257
611
        )
258
612
 
259
613
    def _match_on(self, branch, revs):
260
 
        """
261
 
        Spec for date revisions:
 
614
        """Spec for date revisions:
262
615
          date:value
263
616
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
264
617
          matches the first entry after a given date (either at midnight or
265
618
          at a specified time).
266
 
 
267
 
          So the proper way of saying 'give me all entries for today' is:
268
 
              -r date:today..date:tomorrow
269
619
        """
 
620
        #  XXX: This doesn't actually work
 
621
        #  So the proper way of saying 'give me all entries for today' is:
 
622
        #      -r date:yesterday..date:today
270
623
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
271
624
        if self.spec.lower() == 'yesterday':
272
625
            dt = today - datetime.timedelta(days=1)
277
630
        else:
278
631
            m = self._date_re.match(self.spec)
279
632
            if not m or (not m.group('date') and not m.group('time')):
280
 
                raise BzrError('Invalid revision date %r' % self.spec)
281
 
 
282
 
            if m.group('date'):
283
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
284
 
            else:
285
 
                year, month, day = today.year, today.month, today.day
286
 
            if m.group('time'):
287
 
                hour = int(m.group('hour'))
288
 
                minute = int(m.group('minute'))
289
 
                if m.group('second'):
290
 
                    second = int(m.group('second'))
291
 
                else:
292
 
                    second = 0
293
 
            else:
294
 
                hour, minute, second = 0,0,0
 
633
                raise errors.InvalidRevisionSpec(self.user_spec,
 
634
                                                 branch, 'invalid date')
 
635
 
 
636
            try:
 
637
                if m.group('date'):
 
638
                    year = int(m.group('year'))
 
639
                    month = int(m.group('month'))
 
640
                    day = int(m.group('day'))
 
641
                else:
 
642
                    year = today.year
 
643
                    month = today.month
 
644
                    day = today.day
 
645
 
 
646
                if m.group('time'):
 
647
                    hour = int(m.group('hour'))
 
648
                    minute = int(m.group('minute'))
 
649
                    if m.group('second'):
 
650
                        second = int(m.group('second'))
 
651
                    else:
 
652
                        second = 0
 
653
                else:
 
654
                    hour, minute, second = 0,0,0
 
655
            except ValueError:
 
656
                raise errors.InvalidRevisionSpec(self.user_spec,
 
657
                                                 branch, 'invalid date')
295
658
 
296
659
            dt = datetime.datetime(year=year, month=month, day=day,
297
660
                    hour=hour, minute=minute, second=second)
298
 
        first = dt
299
 
        for i in range(len(revs)):
300
 
            r = branch.get_revision(revs[i])
301
 
            # TODO: Handle timezone.
302
 
            dt = datetime.datetime.fromtimestamp(r.timestamp)
303
 
            if first <= dt:
304
 
                return RevisionInfo(branch, i+1)
305
 
        return RevisionInfo(branch, None)
 
661
        branch.lock_read()
 
662
        try:
 
663
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
664
        finally:
 
665
            branch.unlock()
 
666
        if rev == len(revs):
 
667
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
668
        else:
 
669
            return RevisionInfo(branch, rev + 1)
306
670
 
307
671
SPEC_TYPES.append(RevisionSpec_date)
308
672
 
309
673
 
310
674
class RevisionSpec_ancestor(RevisionSpec):
 
675
    """Selects a common ancestor with a second branch."""
 
676
 
 
677
    help_txt = """Selects a common ancestor with a second branch.
 
678
 
 
679
    Supply the path to a branch to select the common ancestor.
 
680
 
 
681
    The common ancestor is the last revision that existed in both
 
682
    branches. Usually this is the branch point, but it could also be
 
683
    a revision that was merged.
 
684
 
 
685
    This is frequently used with 'diff' to return all of the changes
 
686
    that your branch introduces, while excluding the changes that you
 
687
    have not merged from the remote branch.
 
688
 
 
689
    Examples::
 
690
 
 
691
      ancestor:/path/to/branch
 
692
      $ bzr diff -r ancestor:../../mainline/branch
 
693
    """
311
694
    prefix = 'ancestor:'
312
695
 
313
696
    def _match_on(self, branch, revs):
314
 
        from branch import Branch
315
 
        from revision import common_ancestor, MultipleRevisionSources
316
 
        other_branch = Branch.open_containing(self.spec)[0]
317
 
        revision_a = branch.last_revision()
318
 
        revision_b = other_branch.last_revision()
319
 
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
320
 
            if r is None:
321
 
                raise NoCommits(b)
322
 
        revision_source = MultipleRevisionSources(branch, other_branch)
323
 
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
 
697
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
698
        return self._find_revision_info(branch, self.spec)
 
699
 
 
700
    def _as_revision_id(self, context_branch):
 
701
        return self._find_revision_id(context_branch, self.spec)
 
702
 
 
703
    @staticmethod
 
704
    def _find_revision_info(branch, other_location):
 
705
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
 
706
                                                              other_location)
324
707
        try:
325
 
            revno = branch.revision_id_to_revno(rev_id)
326
 
        except NoSuchRevision:
 
708
            revno = branch.revision_id_to_revno(revision_id)
 
709
        except errors.NoSuchRevision:
327
710
            revno = None
328
 
        return RevisionInfo(branch, revno, rev_id)
329
 
        
 
711
        return RevisionInfo(branch, revno, revision_id)
 
712
 
 
713
    @staticmethod
 
714
    def _find_revision_id(branch, other_location):
 
715
        from bzrlib.branch import Branch
 
716
 
 
717
        branch.lock_read()
 
718
        try:
 
719
            revision_a = revision.ensure_null(branch.last_revision())
 
720
            if revision_a == revision.NULL_REVISION:
 
721
                raise errors.NoCommits(branch)
 
722
            other_branch = Branch.open(other_location)
 
723
            other_branch.lock_read()
 
724
            try:
 
725
                revision_b = revision.ensure_null(other_branch.last_revision())
 
726
                if revision_b == revision.NULL_REVISION:
 
727
                    raise errors.NoCommits(other_branch)
 
728
                graph = branch.repository.get_graph(other_branch.repository)
 
729
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
730
            finally:
 
731
                other_branch.unlock()
 
732
            if rev_id == revision.NULL_REVISION:
 
733
                raise errors.NoCommonAncestor(revision_a, revision_b)
 
734
            return rev_id
 
735
        finally:
 
736
            branch.unlock()
 
737
 
 
738
 
330
739
SPEC_TYPES.append(RevisionSpec_ancestor)
331
740
 
 
741
 
332
742
class RevisionSpec_branch(RevisionSpec):
333
 
    """A branch: revision specifier.
334
 
 
335
 
    This takes the path to a branch and returns its tip revision id.
 
743
    """Selects the last revision of a specified branch."""
 
744
 
 
745
    help_txt = """Selects the last revision of a specified branch.
 
746
 
 
747
    Supply the path to a branch to select its last revision.
 
748
 
 
749
    Examples::
 
750
 
 
751
      branch:/path/to/branch
336
752
    """
337
753
    prefix = 'branch:'
338
754
 
339
755
    def _match_on(self, branch, revs):
340
 
        from branch import Branch
341
 
        from fetch import greedy_fetch
342
 
        other_branch = Branch.open_containing(self.spec)[0]
 
756
        from bzrlib.branch import Branch
 
757
        other_branch = Branch.open(self.spec)
343
758
        revision_b = other_branch.last_revision()
344
 
        if revision_b is None:
345
 
            raise NoCommits(other_branch)
 
759
        if revision_b in (None, revision.NULL_REVISION):
 
760
            raise errors.NoCommits(other_branch)
346
761
        # pull in the remote revisions so we can diff
347
 
        greedy_fetch(branch, other_branch, revision=revision_b)
 
762
        branch.fetch(other_branch, revision_b)
348
763
        try:
349
764
            revno = branch.revision_id_to_revno(revision_b)
350
 
        except NoSuchRevision:
 
765
        except errors.NoSuchRevision:
351
766
            revno = None
352
767
        return RevisionInfo(branch, revno, revision_b)
353
 
        
 
768
 
 
769
    def _as_revision_id(self, context_branch):
 
770
        from bzrlib.branch import Branch
 
771
        other_branch = Branch.open(self.spec)
 
772
        last_revision = other_branch.last_revision()
 
773
        last_revision = revision.ensure_null(last_revision)
 
774
        if last_revision == revision.NULL_REVISION:
 
775
            raise errors.NoCommits(other_branch)
 
776
        return last_revision
 
777
 
354
778
SPEC_TYPES.append(RevisionSpec_branch)
 
779
 
 
780
 
 
781
class RevisionSpec_submit(RevisionSpec_ancestor):
 
782
    """Selects a common ancestor with a submit branch."""
 
783
 
 
784
    help_txt = """Selects a common ancestor with the submit branch.
 
785
 
 
786
    Diffing against this shows all the changes that were made in this branch,
 
787
    and is a good predictor of what merge will do.  The submit branch is
 
788
    used by the bundle and merge directive comands.  If no submit branch
 
789
    is specified, the parent branch is used instead.
 
790
 
 
791
    The common ancestor is the last revision that existed in both
 
792
    branches. Usually this is the branch point, but it could also be
 
793
    a revision that was merged.
 
794
 
 
795
    Examples::
 
796
 
 
797
      $ bzr diff -r submit:
 
798
    """
 
799
 
 
800
    prefix = 'submit:'
 
801
 
 
802
    def _get_submit_location(self, branch):
 
803
        submit_location = branch.get_submit_branch()
 
804
        location_type = 'submit branch'
 
805
        if submit_location is None:
 
806
            submit_location = branch.get_parent()
 
807
            location_type = 'parent branch'
 
808
        if submit_location is None:
 
809
            raise errors.NoSubmitBranch(branch)
 
810
        trace.note('Using %s %s', location_type, submit_location)
 
811
        return submit_location
 
812
 
 
813
    def _match_on(self, branch, revs):
 
814
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
815
        return self._find_revision_info(branch,
 
816
            self._get_submit_location(branch))
 
817
 
 
818
    def _as_revision_id(self, context_branch):
 
819
        return self._find_revision_id(context_branch,
 
820
            self._get_submit_location(context_branch))
 
821
 
 
822
 
 
823
SPEC_TYPES.append(RevisionSpec_submit)