~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Vincent Ladeuil
  • Date: 2007-04-12 14:28:00 UTC
  • mto: (2420.1.1 bzr.http.auth)
  • mto: This revision was merged to the branch mainline in revision 2463.
  • Revision ID: v.ladeuil+lp@free.fr-20070412142800-6e1pc8aksxlp7pg4
Fix tests around stdin emptyness.

* bzrlib/tests/test_ui.py:
Use readline not getline and test '' not None.

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
        try:
 
104
            revno = revs.index(revision_id) + 1
 
105
        except ValueError:
 
106
            revno = None
 
107
        return RevisionInfo(branch, revno, revision_id)
 
108
 
 
109
 
84
110
# classes in this list should have a "prefix" attribute, against which
85
111
# string specs are matched
86
112
SPEC_TYPES = []
 
113
_revno_regex = None
 
114
 
87
115
 
88
116
class RevisionSpec(object):
89
 
    """A parsed revision specification.
 
117
    """A parsed revision specification."""
 
118
 
 
119
    help_txt = """A parsed revision specification.
90
120
 
91
121
    A revision specification can be an integer, in which case it is
92
122
    assumed to be a revno (though this will translate negative values
104
134
 
105
135
    prefix = None
106
136
 
107
 
    def __new__(cls, spec, foo=_marker):
108
 
        """Parse a revision specifier.
 
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)
 
147
 
 
148
    @staticmethod
 
149
    def from_string(spec):
 
150
        """Parse a revision spec string into a RevisionSpec object.
 
151
 
 
152
        :param spec: A string specified by the user
 
153
        :return: A RevisionSpec object that understands how to parse the
 
154
            supplied notation.
109
155
        """
 
156
        if not isinstance(spec, (type(None), basestring)):
 
157
            raise TypeError('error')
 
158
 
110
159
        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)
 
160
            return RevisionSpec(None, _internal=True)
 
161
 
 
162
        assert isinstance(spec, basestring), \
 
163
            "You should only supply strings not %s" % (type(spec),)
 
164
 
 
165
        for spectype in SPEC_TYPES:
 
166
            if spec.startswith(spectype.prefix):
 
167
                trace.mutter('Returning RevisionSpec %s for %s',
 
168
                             spectype.__name__, spec)
 
169
                return spectype(spec, _internal=True)
127
170
        else:
128
 
            raise TypeError('Unhandled revision type %s' % spec)
129
 
 
130
 
    def __init__(self, spec):
 
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)
 
182
 
 
183
    def __init__(self, spec, _internal=False):
 
184
        """Create a RevisionSpec referring to the Null revision.
 
185
 
 
186
        :param spec: The original spec supplied by the user
 
187
        :param _internal: Used to ensure that RevisionSpec is not being
 
188
            called directly. Only from RevisionSpec.from_string()
 
189
        """
 
190
        if not _internal:
 
191
            # XXX: Update this after 0.10 is released
 
192
            symbol_versioning.warn('Creating a RevisionSpec directly has'
 
193
                                   ' been deprecated in version 0.11. Use'
 
194
                                   ' RevisionSpec.from_string()'
 
195
                                   ' instead.',
 
196
                                   DeprecationWarning, stacklevel=2)
 
197
        self.user_spec = spec
131
198
        if self.prefix and spec.startswith(self.prefix):
132
199
            spec = spec[len(self.prefix):]
133
200
        self.spec = spec
134
201
 
135
202
    def _match_on(self, branch, revs):
 
203
        trace.mutter('Returning RevisionSpec._match_on: None')
136
204
        return RevisionInfo(branch, 0, None)
137
205
 
138
206
    def _match_on_and_check(self, branch, revs):
143
211
            # special case - the empty tree
144
212
            return info
145
213
        elif self.prefix:
146
 
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
 
214
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
147
215
        else:
148
 
            raise NoSuchRevision(branch, str(self.spec))
 
216
            raise errors.InvalidRevisionSpec(self.spec, branch)
149
217
 
150
218
    def in_history(self, branch):
151
 
        revs = branch.revision_history()
 
219
        if branch:
 
220
            revs = branch.revision_history()
 
221
        else:
 
222
            # this should never trigger.
 
223
            # TODO: make it a deprecated code path. RBC 20060928
 
224
            revs = None
152
225
        return self._match_on_and_check(branch, revs)
153
226
 
154
227
        # FIXME: in_history is somewhat broken,
163
236
        
164
237
    def __repr__(self):
165
238
        # this is mostly for helping with testing
166
 
        return '<%s %s%s>' % (self.__class__.__name__,
167
 
                              self.prefix or '',
168
 
                              self.spec)
 
239
        return '<%s %s>' % (self.__class__.__name__,
 
240
                              self.user_spec)
 
241
    
 
242
    def needs_branch(self):
 
243
        """Whether this revision spec needs a branch.
 
244
 
 
245
        Set this to False the branch argument of _match_on is not used.
 
246
        """
 
247
        return True
 
248
 
 
249
    def get_branch(self):
 
250
        """When the revision specifier contains a branch location, return it.
 
251
        
 
252
        Otherwise, return None.
 
253
        """
 
254
        return None
169
255
 
170
256
 
171
257
# private API
172
258
 
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
259
class RevisionSpec_revno(RevisionSpec):
 
260
    """Selects a revision using a number."""
 
261
 
 
262
    help_txt = """Selects a revision using a number.
 
263
 
 
264
    Use an integer to specify a revision in the history of the branch.
 
265
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
266
    A negative number will count from the end of the branch (-1 is the
 
267
    last revision, -2 the previous one). If the negative number is larger
 
268
    than the branch's history, the first revision is returned.
 
269
    examples:
 
270
      revno:1                   -> return the first revision
 
271
      revno:3:/path/to/branch   -> return the 3rd revision of
 
272
                                   the branch '/path/to/branch'
 
273
      revno:-1                  -> The last revision in a branch.
 
274
      -2:http://other/branch    -> The second to last revision in the
 
275
                                   remote branch.
 
276
      -1000000                  -> Most likely the first revision, unless
 
277
                                   your history is very long.
 
278
    """
188
279
    prefix = 'revno:'
189
280
 
190
281
    def _match_on(self, branch, revs):
191
282
        """Lookup a revision by revision number"""
192
 
        try:
193
 
            return RevisionInfo(branch, int(self.spec))
194
 
        except ValueError:
195
 
            return RevisionInfo(branch, None)
 
283
        loc = self.spec.find(':')
 
284
        if loc == -1:
 
285
            revno_spec = self.spec
 
286
            branch_spec = None
 
287
        else:
 
288
            revno_spec = self.spec[:loc]
 
289
            branch_spec = self.spec[loc+1:]
 
290
 
 
291
        if revno_spec == '':
 
292
            if not branch_spec:
 
293
                raise errors.InvalidRevisionSpec(self.user_spec,
 
294
                        branch, 'cannot have an empty revno and no branch')
 
295
            revno = None
 
296
        else:
 
297
            try:
 
298
                revno = int(revno_spec)
 
299
                dotted = False
 
300
            except ValueError:
 
301
                # dotted decimal. This arguably should not be here
 
302
                # but the from_string method is a little primitive 
 
303
                # right now - RBC 20060928
 
304
                try:
 
305
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
 
306
                except ValueError, e:
 
307
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
308
 
 
309
                dotted = True
 
310
 
 
311
        if branch_spec:
 
312
            # the user has override the branch to look in.
 
313
            # we need to refresh the revision_history map and
 
314
            # the branch object.
 
315
            from bzrlib.branch import Branch
 
316
            branch = Branch.open(branch_spec)
 
317
            # Need to use a new revision history
 
318
            # because we are using a specific branch
 
319
            revs = branch.revision_history()
 
320
 
 
321
        if dotted:
 
322
            branch.lock_read()
 
323
            try:
 
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)
 
336
            else:
 
337
                # there is no traditional 'revno' for dotted-decimal revnos.
 
338
                # so for  API compatability we return None.
 
339
                return RevisionInfo(branch, None, revisions[0][1])
 
340
        else:
 
341
            if revno < 0:
 
342
                # if get_rev_id supported negative revnos, there would not be a
 
343
                # need for this special case.
 
344
                if (-revno) >= len(revs):
 
345
                    revno = 1
 
346
                else:
 
347
                    revno = len(revs) + revno + 1
 
348
            try:
 
349
                revision_id = branch.get_rev_id(revno, revs)
 
350
            except errors.NoSuchRevision:
 
351
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
352
        return RevisionInfo(branch, revno, revision_id)
 
353
        
 
354
    def needs_branch(self):
 
355
        return self.spec.find(':') == -1
 
356
 
 
357
    def get_branch(self):
 
358
        if self.spec.find(':') == -1:
 
359
            return None
 
360
        else:
 
361
            return self.spec[self.spec.find(':')+1:]
 
362
 
 
363
# Old compatibility 
 
364
RevisionSpec_int = RevisionSpec_revno
196
365
 
197
366
SPEC_TYPES.append(RevisionSpec_revno)
198
367
 
199
368
 
200
369
class RevisionSpec_revid(RevisionSpec):
 
370
    """Selects a revision using the revision id."""
 
371
 
 
372
    help_txt = """Selects a revision using the revision id.
 
373
 
 
374
    Supply a specific revision id, that can be used to specify any
 
375
    revision id in the ancestry of the branch. 
 
376
    Including merges, and pending merges.
 
377
    examples:
 
378
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
 
379
    """    
201
380
    prefix = 'revid:'
202
381
 
203
382
    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)
 
383
        # self.spec comes straight from parsing the command line arguments,
 
384
        # so we expect it to be a Unicode string. Switch it to the internal
 
385
        # representation.
 
386
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
387
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
208
388
 
209
389
SPEC_TYPES.append(RevisionSpec_revid)
210
390
 
211
391
 
212
392
class RevisionSpec_last(RevisionSpec):
 
393
    """Selects the nth revision from the end."""
 
394
 
 
395
    help_txt = """Selects the nth revision from the end.
 
396
 
 
397
    Supply a positive number to get the nth revision from the end.
 
398
    This is the same as supplying negative numbers to the 'revno:' spec.
 
399
    examples:
 
400
      last:1        -> return the last revision
 
401
      last:3        -> return the revision 2 before the end.
 
402
    """    
213
403
 
214
404
    prefix = 'last:'
215
405
 
216
406
    def _match_on(self, branch, revs):
 
407
        if self.spec == '':
 
408
            if not revs:
 
409
                raise errors.NoCommits(branch)
 
410
            return RevisionInfo(branch, len(revs), revs[-1])
 
411
 
217
412
        try:
218
413
            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)
 
414
        except ValueError, e:
 
415
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
416
 
 
417
        if offset <= 0:
 
418
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
419
                                             'you must supply a positive value')
 
420
        revno = len(revs) - offset + 1
 
421
        try:
 
422
            revision_id = branch.get_rev_id(revno, revs)
 
423
        except errors.NoSuchRevision:
 
424
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
425
        return RevisionInfo(branch, revno, revision_id)
225
426
 
226
427
SPEC_TYPES.append(RevisionSpec_last)
227
428
 
228
429
 
229
430
class RevisionSpec_before(RevisionSpec):
 
431
    """Selects the parent of the revision specified."""
 
432
 
 
433
    help_txt = """Selects the parent of the revision specified.
 
434
 
 
435
    Supply any revision spec to return the parent of that revision.
 
436
    It is an error to request the parent of the null revision (before:0).
 
437
    This is mostly useful when inspecting revisions that are not in the
 
438
    revision history of a branch.
 
439
 
 
440
    examples:
 
441
      before:1913    -> Return the parent of revno 1913 (revno 1912)
 
442
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
 
443
                                            aaaa@bbbb-1234567890
 
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)
 
447
    """
230
448
 
231
449
    prefix = 'before:'
232
450
    
233
451
    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)
 
452
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
 
453
        if r.revno == 0:
 
454
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
455
                                         'cannot go before the null: revision')
 
456
        if r.revno is None:
 
457
            # We need to use the repository history here
 
458
            rev = branch.repository.get_revision(r.rev_id)
 
459
            if not rev.parent_ids:
 
460
                revno = 0
 
461
                revision_id = None
 
462
            else:
 
463
                revision_id = rev.parent_ids[0]
 
464
                try:
 
465
                    revno = revs.index(revision_id) + 1
 
466
                except ValueError:
 
467
                    revno = None
 
468
        else:
 
469
            revno = r.revno - 1
 
470
            try:
 
471
                revision_id = branch.get_rev_id(revno, revs)
 
472
            except errors.NoSuchRevision:
 
473
                raise errors.InvalidRevisionSpec(self.user_spec,
 
474
                                                 branch)
 
475
        return RevisionInfo(branch, revno, revision_id)
238
476
 
239
477
SPEC_TYPES.append(RevisionSpec_before)
240
478
 
241
479
 
242
480
class RevisionSpec_tag(RevisionSpec):
 
481
    """Select a revision identified by tag name"""
 
482
 
 
483
    help_txt = """Selects a revision identified by a tag name.
 
484
 
 
485
    Tags are stored in the branch and created by the 'tag' command.
 
486
    """
 
487
 
243
488
    prefix = 'tag:'
244
489
 
245
490
    def _match_on(self, branch, revs):
246
 
        raise BzrError('tag: namespace registered, but not implemented.')
 
491
        # Can raise tags not supported, NoSuchTag, etc
 
492
        return RevisionInfo.from_revision_id(branch,
 
493
            branch.tags.lookup_tag(self.spec),
 
494
            revs)
247
495
 
248
496
SPEC_TYPES.append(RevisionSpec_tag)
249
497
 
250
498
 
 
499
class _RevListToTimestamps(object):
 
500
    """This takes a list of revisions, and allows you to bisect by date"""
 
501
 
 
502
    __slots__ = ['revs', 'branch']
 
503
 
 
504
    def __init__(self, revs, branch):
 
505
        self.revs = revs
 
506
        self.branch = branch
 
507
 
 
508
    def __getitem__(self, index):
 
509
        """Get the date of the index'd item"""
 
510
        r = self.branch.repository.get_revision(self.revs[index])
 
511
        # TODO: Handle timezone.
 
512
        return datetime.datetime.fromtimestamp(r.timestamp)
 
513
 
 
514
    def __len__(self):
 
515
        return len(self.revs)
 
516
 
 
517
 
251
518
class RevisionSpec_date(RevisionSpec):
 
519
    """Selects a revision on the basis of a datestamp."""
 
520
 
 
521
    help_txt = """Selects a revision on the basis of a datestamp.
 
522
 
 
523
    Supply a datestamp to select the first revision that matches the date.
 
524
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
525
    Matches the first entry after a given date (either at midnight or
 
526
    at a specified time).
 
527
 
 
528
    One way to display all the changes since yesterday would be:
 
529
        bzr log -r date:yesterday..-1
 
530
 
 
531
    examples:
 
532
      date:yesterday            -> select the first revision since yesterday
 
533
      date:2006-08-14,17:10:14  -> select the first revision after
 
534
                                   August 14th, 2006 at 5:10pm.
 
535
    """    
252
536
    prefix = 'date:'
253
537
    _date_re = re.compile(
254
538
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
257
541
        )
258
542
 
259
543
    def _match_on(self, branch, revs):
260
 
        """
261
 
        Spec for date revisions:
 
544
        """Spec for date revisions:
262
545
          date:value
263
546
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
264
547
          matches the first entry after a given date (either at midnight or
265
548
          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
549
        """
 
550
        #  XXX: This doesn't actually work
 
551
        #  So the proper way of saying 'give me all entries for today' is:
 
552
        #      -r date:yesterday..date:today
270
553
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
271
554
        if self.spec.lower() == 'yesterday':
272
555
            dt = today - datetime.timedelta(days=1)
277
560
        else:
278
561
            m = self._date_re.match(self.spec)
279
562
            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
 
563
                raise errors.InvalidRevisionSpec(self.user_spec,
 
564
                                                 branch, 'invalid date')
 
565
 
 
566
            try:
 
567
                if m.group('date'):
 
568
                    year = int(m.group('year'))
 
569
                    month = int(m.group('month'))
 
570
                    day = int(m.group('day'))
 
571
                else:
 
572
                    year = today.year
 
573
                    month = today.month
 
574
                    day = today.day
 
575
 
 
576
                if m.group('time'):
 
577
                    hour = int(m.group('hour'))
 
578
                    minute = int(m.group('minute'))
 
579
                    if m.group('second'):
 
580
                        second = int(m.group('second'))
 
581
                    else:
 
582
                        second = 0
 
583
                else:
 
584
                    hour, minute, second = 0,0,0
 
585
            except ValueError:
 
586
                raise errors.InvalidRevisionSpec(self.user_spec,
 
587
                                                 branch, 'invalid date')
295
588
 
296
589
            dt = datetime.datetime(year=year, month=month, day=day,
297
590
                    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)
 
591
        branch.lock_read()
 
592
        try:
 
593
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
594
        finally:
 
595
            branch.unlock()
 
596
        if rev == len(revs):
 
597
            return RevisionInfo(branch, None)
 
598
        else:
 
599
            return RevisionInfo(branch, rev + 1)
306
600
 
307
601
SPEC_TYPES.append(RevisionSpec_date)
308
602
 
309
603
 
310
604
class RevisionSpec_ancestor(RevisionSpec):
 
605
    """Selects a common ancestor with a second branch."""
 
606
 
 
607
    help_txt = """Selects a common ancestor with a second branch.
 
608
 
 
609
    Supply the path to a branch to select the common ancestor.
 
610
 
 
611
    The common ancestor is the last revision that existed in both
 
612
    branches. Usually this is the branch point, but it could also be
 
613
    a revision that was merged.
 
614
 
 
615
    This is frequently used with 'diff' to return all of the changes
 
616
    that your branch introduces, while excluding the changes that you
 
617
    have not merged from the remote branch.
 
618
 
 
619
    examples:
 
620
      ancestor:/path/to/branch
 
621
      $ bzr diff -r ancestor:../../mainline/branch
 
622
    """
311
623
    prefix = 'ancestor:'
312
624
 
313
625
    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]
 
626
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
627
        return self._find_revision_info(branch, self.spec)
 
628
 
 
629
    @staticmethod
 
630
    def _find_revision_info(branch, other_location):
 
631
        from bzrlib.branch import Branch
 
632
 
 
633
        other_branch = Branch.open(other_location)
317
634
        revision_a = branch.last_revision()
318
635
        revision_b = other_branch.last_revision()
319
636
        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)
 
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)
324
643
        try:
325
644
            revno = branch.revision_id_to_revno(rev_id)
326
 
        except NoSuchRevision:
 
645
        except errors.NoSuchRevision:
327
646
            revno = None
328
647
        return RevisionInfo(branch, revno, rev_id)
329
 
        
 
648
 
 
649
 
330
650
SPEC_TYPES.append(RevisionSpec_ancestor)
331
651
 
 
652
 
332
653
class RevisionSpec_branch(RevisionSpec):
333
 
    """A branch: revision specifier.
334
 
 
335
 
    This takes the path to a branch and returns its tip revision id.
 
654
    """Selects the last revision of a specified branch."""
 
655
 
 
656
    help_txt = """Selects the last revision of a specified branch.
 
657
 
 
658
    Supply the path to a branch to select its last revision.
 
659
 
 
660
    examples:
 
661
      branch:/path/to/branch
336
662
    """
337
663
    prefix = 'branch:'
338
664
 
339
665
    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]
 
666
        from bzrlib.branch import Branch
 
667
        other_branch = Branch.open(self.spec)
343
668
        revision_b = other_branch.last_revision()
344
 
        if revision_b is None:
345
 
            raise NoCommits(other_branch)
 
669
        if revision_b in (None, revision.NULL_REVISION):
 
670
            raise errors.NoCommits(other_branch)
346
671
        # pull in the remote revisions so we can diff
347
 
        greedy_fetch(branch, other_branch, revision=revision_b)
 
672
        branch.fetch(other_branch, revision_b)
348
673
        try:
349
674
            revno = branch.revision_id_to_revno(revision_b)
350
 
        except NoSuchRevision:
 
675
        except errors.NoSuchRevision:
351
676
            revno = None
352
677
        return RevisionInfo(branch, revno, revision_b)
353
678
        
354
679
SPEC_TYPES.append(RevisionSpec_branch)
 
680
 
 
681
 
 
682
class RevisionSpec_submit(RevisionSpec_ancestor):
 
683
    """Selects a common ancestor with a submit branch."""
 
684
 
 
685
    help_txt = """Selects a common ancestor with the submit branch.
 
686
 
 
687
    Diffing against this shows all the changes that were made in this branch,
 
688
    and is a good predictor of what merge will do.  The submit branch is
 
689
    used by the bundle and merge directive comands.  If no submit branch
 
690
    is specified, the parent branch is used instead.
 
691
 
 
692
    The common ancestor is the last revision that existed in both
 
693
    branches. Usually this is the branch point, but it could also be
 
694
    a revision that was merged.
 
695
 
 
696
    examples:
 
697
      $ bzr diff -r submit:
 
698
    """
 
699
 
 
700
    prefix = 'submit:'
 
701
 
 
702
    def _match_on(self, branch, revs):
 
703
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
704
        submit_location = branch.get_submit_branch()
 
705
        location_type = 'submit branch'
 
706
        if submit_location is None:
 
707
            submit_location = branch.get_parent()
 
708
            location_type = 'parent branch'
 
709
        if submit_location is None:
 
710
            raise errors.NoSubmitBranch(branch)
 
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)