~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

Merge in upstream.

Show diffs side-by-side

added added

removed removed

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