~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Pool
  • Date: 2005-09-30 05:56:05 UTC
  • mto: (1185.14.2)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: mbp@sourcefrog.net-20050930055605-a2c534529b392a7d
- fix upgrade for transport changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Canonical Ltd
2
 
#
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
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
 
    revision,
25
 
    symbol_versioning,
26
 
    trace,
27
 
    tsort,
28
 
    )
29
 
 
 
20
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
30
21
 
31
22
_marker = []
32
23
 
33
 
 
34
24
class RevisionInfo(object):
35
 
    """The results of applying a revision specification to a branch."""
36
 
 
37
 
    help_txt = """The results of applying a revision specification to a branch.
 
25
    """The results of applying a revision specification to a branch.
38
26
 
39
27
    An instance has two useful attributes: revno, and rev_id.
40
28
 
69
57
        # TODO: otherwise, it should depend on how I was built -
70
58
        # if it's in_history(branch), then check revision_history(),
71
59
        # if it's in_store(branch), do the check below
72
 
        return self.branch.repository.has_revision(self.rev_id)
 
60
        return self.rev_id in self.branch.revision_store
73
61
 
74
62
    def __len__(self):
75
63
        return 2
80
68
        raise IndexError(index)
81
69
 
82
70
    def get(self):
83
 
        return self.branch.repository.get_revision(self.rev_id)
 
71
        return self.branch.get_revision(self.rev_id)
84
72
 
85
73
    def __eq__(self, other):
86
74
        if type(other) not in (tuple, list, type(self)):
93
81
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
94
82
            self.revno, self.rev_id, self.branch)
95
83
 
96
 
 
97
84
# classes in this list should have a "prefix" attribute, against which
98
85
# string specs are matched
99
86
SPEC_TYPES = []
100
 
_revno_regex = None
101
 
 
102
87
 
103
88
class RevisionSpec(object):
104
 
    """A parsed revision specification."""
105
 
 
106
 
    help_txt = """A parsed revision specification.
 
89
    """A parsed revision specification.
107
90
 
108
91
    A revision specification can be an integer, in which case it is
109
92
    assumed to be a revno (though this will translate negative values
121
104
 
122
105
    prefix = None
123
106
 
124
 
    def __new__(cls, spec, _internal=False):
125
 
        if _internal:
126
 
            return object.__new__(cls, spec, _internal=_internal)
127
 
 
128
 
        symbol_versioning.warn('Creating a RevisionSpec directly has'
129
 
                               ' been deprecated in version 0.11. Use'
130
 
                               ' RevisionSpec.from_string()'
131
 
                               ' instead.',
132
 
                               DeprecationWarning, stacklevel=2)
133
 
        return RevisionSpec.from_string(spec)
134
 
 
135
 
    @staticmethod
136
 
    def from_string(spec):
137
 
        """Parse a revision spec string into a RevisionSpec object.
138
 
 
139
 
        :param spec: A string specified by the user
140
 
        :return: A RevisionSpec object that understands how to parse the
141
 
            supplied notation.
 
107
    def __new__(cls, spec, foo=_marker):
 
108
        """Parse a revision specifier.
142
109
        """
143
 
        if not isinstance(spec, (type(None), basestring)):
144
 
            raise TypeError('error')
145
 
 
146
110
        if spec is None:
147
 
            return RevisionSpec(None, _internal=True)
148
 
 
149
 
        assert isinstance(spec, basestring), \
150
 
            "You should only supply strings not %s" % (type(spec),)
151
 
 
152
 
        for spectype in SPEC_TYPES:
153
 
            if spec.startswith(spectype.prefix):
154
 
                trace.mutter('Returning RevisionSpec %s for %s',
155
 
                             spectype.__name__, spec)
156
 
                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)
157
127
        else:
158
 
            # RevisionSpec_revno is special cased, because it is the only
159
 
            # one that directly handles plain integers
160
 
            # TODO: This should not be special cased rather it should be
161
 
            # a method invocation on spectype.canparse()
162
 
            global _revno_regex
163
 
            if _revno_regex is None:
164
 
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
165
 
            if _revno_regex.match(spec) is not None:
166
 
                return RevisionSpec_revno(spec, _internal=True)
167
 
 
168
 
            raise errors.NoSuchRevisionSpec(spec)
169
 
 
170
 
    def __init__(self, spec, _internal=False):
171
 
        """Create a RevisionSpec referring to the Null revision.
172
 
 
173
 
        :param spec: The original spec supplied by the user
174
 
        :param _internal: Used to ensure that RevisionSpec is not being
175
 
            called directly. Only from RevisionSpec.from_string()
176
 
        """
177
 
        if not _internal:
178
 
            # XXX: Update this after 0.10 is released
179
 
            symbol_versioning.warn('Creating a RevisionSpec directly has'
180
 
                                   ' been deprecated in version 0.11. Use'
181
 
                                   ' RevisionSpec.from_string()'
182
 
                                   ' instead.',
183
 
                                   DeprecationWarning, stacklevel=2)
184
 
        self.user_spec = spec
 
128
            raise TypeError('Unhandled revision type %s' % spec)
 
129
 
 
130
    def __init__(self, spec):
185
131
        if self.prefix and spec.startswith(self.prefix):
186
132
            spec = spec[len(self.prefix):]
187
133
        self.spec = spec
188
134
 
189
135
    def _match_on(self, branch, revs):
190
 
        trace.mutter('Returning RevisionSpec._match_on: None')
191
136
        return RevisionInfo(branch, 0, None)
192
137
 
193
138
    def _match_on_and_check(self, branch, revs):
198
143
            # special case - the empty tree
199
144
            return info
200
145
        elif self.prefix:
201
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
146
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
202
147
        else:
203
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
 
148
            raise NoSuchRevision(branch, str(self.spec))
204
149
 
205
150
    def in_history(self, branch):
206
 
        if branch:
207
 
            revs = branch.revision_history()
208
 
        else:
209
 
            # this should never trigger.
210
 
            # TODO: make it a deprecated code path. RBC 20060928
211
 
            revs = None
 
151
        revs = branch.revision_history()
212
152
        return self._match_on_and_check(branch, revs)
213
153
 
214
 
        # FIXME: in_history is somewhat broken,
215
 
        # it will return non-history revisions in many
216
 
        # circumstances. The expected facility is that
217
 
        # in_history only returns revision-history revs,
218
 
        # in_store returns any rev. RBC 20051010
219
 
    # aliases for now, when we fix the core logic, then they
220
 
    # will do what you expect.
221
 
    in_store = in_history
222
 
    in_branch = in_store
223
 
        
224
154
    def __repr__(self):
225
155
        # this is mostly for helping with testing
226
 
        return '<%s %s>' % (self.__class__.__name__,
227
 
                              self.user_spec)
228
 
    
229
 
    def needs_branch(self):
230
 
        """Whether this revision spec needs a branch.
231
 
 
232
 
        Set this to False the branch argument of _match_on is not used.
233
 
        """
234
 
        return True
235
 
 
236
 
    def get_branch(self):
237
 
        """When the revision specifier contains a branch location, return it.
238
 
        
239
 
        Otherwise, return None.
240
 
        """
241
 
        return None
 
156
        return '<%s %s%s>' % (self.__class__.__name__,
 
157
                              self.prefix or '',
 
158
                              self.spec)
242
159
 
243
160
 
244
161
# private API
245
162
 
 
163
class RevisionSpec_int(RevisionSpec):
 
164
    """Spec is a number.  Special case."""
 
165
    def __init__(self, spec):
 
166
        self.spec = int(spec)
 
167
 
 
168
    def _match_on(self, branch, revs):
 
169
        if self.spec < 0:
 
170
            revno = len(revs) + self.spec + 1
 
171
        else:
 
172
            revno = self.spec
 
173
        rev_id = branch.get_rev_id(revno, revs)
 
174
        return RevisionInfo(branch, revno, rev_id)
 
175
 
 
176
 
246
177
class RevisionSpec_revno(RevisionSpec):
247
 
    """Selects a revision using a number."""
248
 
 
249
 
    help_txt = """Selects a revision using a number.
250
 
 
251
 
    Use an integer to specify a revision in the history of the branch.
252
 
    Optionally a branch can be specified. The 'revno:' prefix is optional.
253
 
    A negative number will count from the end of the branch (-1 is the
254
 
    last revision, -2 the previous one). If the negative number is larger
255
 
    than the branch's history, the first revision is returned.
256
 
    examples:
257
 
      revno:1                   -> return the first revision
258
 
      revno:3:/path/to/branch   -> return the 3rd revision of
259
 
                                   the branch '/path/to/branch'
260
 
      revno:-1                  -> The last revision in a branch.
261
 
      -2:http://other/branch    -> The second to last revision in the
262
 
                                   remote branch.
263
 
      -1000000                  -> Most likely the first revision, unless
264
 
                                   your history is very long.
265
 
    """
266
178
    prefix = 'revno:'
267
179
 
268
180
    def _match_on(self, branch, revs):
269
181
        """Lookup a revision by revision number"""
270
 
        loc = self.spec.find(':')
271
 
        if loc == -1:
272
 
            revno_spec = self.spec
273
 
            branch_spec = None
274
 
        else:
275
 
            revno_spec = self.spec[:loc]
276
 
            branch_spec = self.spec[loc+1:]
277
 
 
278
 
        if revno_spec == '':
279
 
            if not branch_spec:
280
 
                raise errors.InvalidRevisionSpec(self.user_spec,
281
 
                        branch, 'cannot have an empty revno and no branch')
282
 
            revno = None
283
 
        else:
284
 
            try:
285
 
                revno = int(revno_spec)
286
 
                dotted = False
287
 
            except ValueError:
288
 
                # dotted decimal. This arguably should not be here
289
 
                # but the from_string method is a little primitive 
290
 
                # right now - RBC 20060928
291
 
                try:
292
 
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
293
 
                except ValueError, e:
294
 
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
295
 
 
296
 
                dotted = True
297
 
 
298
 
        if branch_spec:
299
 
            # the user has override the branch to look in.
300
 
            # we need to refresh the revision_history map and
301
 
            # the branch object.
302
 
            from bzrlib.branch import Branch
303
 
            branch = Branch.open(branch_spec)
304
 
            # Need to use a new revision history
305
 
            # because we are using a specific branch
306
 
            revs = branch.revision_history()
307
 
 
308
 
        if dotted:
309
 
            branch.lock_read()
310
 
            try:
311
 
                last_rev = branch.last_revision()
312
 
                merge_sorted_revisions = tsort.merge_sort(
313
 
                    branch.repository.get_revision_graph(last_rev),
314
 
                    last_rev,
315
 
                    generate_revno=True)
316
 
                def match(item):
317
 
                    return item[3] == match_revno
318
 
                revisions = filter(match, merge_sorted_revisions)
319
 
            finally:
320
 
                branch.unlock()
321
 
            if len(revisions) != 1:
322
 
                return RevisionInfo(branch, None, None)
323
 
            else:
324
 
                # there is no traditional 'revno' for dotted-decimal revnos.
325
 
                # so for  API compatability we return None.
326
 
                return RevisionInfo(branch, None, revisions[0][1])
327
 
        else:
328
 
            if revno < 0:
329
 
                # if get_rev_id supported negative revnos, there would not be a
330
 
                # need for this special case.
331
 
                if (-revno) >= len(revs):
332
 
                    revno = 1
333
 
                else:
334
 
                    revno = len(revs) + revno + 1
335
 
            try:
336
 
                revision_id = branch.get_rev_id(revno, revs)
337
 
            except errors.NoSuchRevision:
338
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
339
 
        return RevisionInfo(branch, revno, revision_id)
340
 
        
341
 
    def needs_branch(self):
342
 
        return self.spec.find(':') == -1
343
 
 
344
 
    def get_branch(self):
345
 
        if self.spec.find(':') == -1:
346
 
            return None
347
 
        else:
348
 
            return self.spec[self.spec.find(':')+1:]
349
 
 
350
 
# Old compatibility 
351
 
RevisionSpec_int = RevisionSpec_revno
 
182
        try:
 
183
            return RevisionInfo(branch, int(self.spec))
 
184
        except ValueError:
 
185
            return RevisionInfo(branch, None)
352
186
 
353
187
SPEC_TYPES.append(RevisionSpec_revno)
354
188
 
355
189
 
356
190
class RevisionSpec_revid(RevisionSpec):
357
 
    """Selects a revision using the revision id."""
358
 
 
359
 
    help_txt = """Selects a revision using the revision id.
360
 
 
361
 
    Supply a specific revision id, that can be used to specify any
362
 
    revision id in the ancestry of the branch. 
363
 
    Including merges, and pending merges.
364
 
    examples:
365
 
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
366
 
    """    
367
191
    prefix = 'revid:'
368
192
 
369
193
    def _match_on(self, branch, revs):
370
194
        try:
371
 
            revno = revs.index(self.spec) + 1
 
195
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
372
196
        except ValueError:
373
 
            revno = None
374
 
        return RevisionInfo(branch, revno, self.spec)
 
197
            return RevisionInfo(branch, None)
375
198
 
376
199
SPEC_TYPES.append(RevisionSpec_revid)
377
200
 
378
201
 
379
202
class RevisionSpec_last(RevisionSpec):
380
 
    """Selects the nth revision from the end."""
381
 
 
382
 
    help_txt = """Selects the nth revision from the end.
383
 
 
384
 
    Supply a positive number to get the nth revision from the end.
385
 
    This is the same as supplying negative numbers to the 'revno:' spec.
386
 
    examples:
387
 
      last:1        -> return the last revision
388
 
      last:3        -> return the revision 2 before the end.
389
 
    """    
390
203
 
391
204
    prefix = 'last:'
392
205
 
393
206
    def _match_on(self, branch, revs):
394
 
        if self.spec == '':
395
 
            if not revs:
396
 
                raise errors.NoCommits(branch)
397
 
            return RevisionInfo(branch, len(revs), revs[-1])
398
 
 
399
207
        try:
400
208
            offset = int(self.spec)
401
 
        except ValueError, e:
402
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
403
 
 
404
 
        if offset <= 0:
405
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
406
 
                                             'you must supply a positive value')
407
 
        revno = len(revs) - offset + 1
408
 
        try:
409
 
            revision_id = branch.get_rev_id(revno, revs)
410
 
        except errors.NoSuchRevision:
411
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
412
 
        return RevisionInfo(branch, revno, revision_id)
 
209
        except ValueError:
 
210
            return RevisionInfo(branch, None)
 
211
        else:
 
212
            if offset <= 0:
 
213
                raise BzrError('You must supply a positive value for --revision last:XXX')
 
214
            return RevisionInfo(branch, len(revs) - offset + 1)
413
215
 
414
216
SPEC_TYPES.append(RevisionSpec_last)
415
217
 
416
218
 
417
219
class RevisionSpec_before(RevisionSpec):
418
 
    """Selects the parent of the revision specified."""
419
 
 
420
 
    help_txt = """Selects the parent of the revision specified.
421
 
 
422
 
    Supply any revision spec to return the parent of that revision.
423
 
    It is an error to request the parent of the null revision (before:0).
424
 
    This is mostly useful when inspecting revisions that are not in the
425
 
    revision history of a branch.
426
 
 
427
 
    examples:
428
 
      before:1913    -> Return the parent of revno 1913 (revno 1912)
429
 
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
430
 
                                            aaaa@bbbb-1234567890
431
 
      bzr diff -r before:revid:aaaa..revid:aaaa
432
 
            -> Find the changes between revision 'aaaa' and its parent.
433
 
               (what changes did 'aaaa' introduce)
434
 
    """
435
220
 
436
221
    prefix = 'before:'
437
222
    
438
223
    def _match_on(self, branch, revs):
439
 
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
440
 
        if r.revno == 0:
441
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
442
 
                                         'cannot go before the null: revision')
443
 
        if r.revno is None:
444
 
            # We need to use the repository history here
445
 
            rev = branch.repository.get_revision(r.rev_id)
446
 
            if not rev.parent_ids:
447
 
                revno = 0
448
 
                revision_id = None
449
 
            else:
450
 
                revision_id = rev.parent_ids[0]
451
 
                try:
452
 
                    revno = revs.index(revision_id) + 1
453
 
                except ValueError:
454
 
                    revno = None
455
 
        else:
456
 
            revno = r.revno - 1
457
 
            try:
458
 
                revision_id = branch.get_rev_id(revno, revs)
459
 
            except errors.NoSuchRevision:
460
 
                raise errors.InvalidRevisionSpec(self.user_spec,
461
 
                                                 branch)
462
 
        return RevisionInfo(branch, revno, revision_id)
 
224
        r = RevisionSpec(self.spec)._match_on(branch, revs)
 
225
        if (r.revno is None) or (r.revno == 0):
 
226
            return r
 
227
        return RevisionInfo(branch, r.revno - 1)
463
228
 
464
229
SPEC_TYPES.append(RevisionSpec_before)
465
230
 
466
231
 
467
232
class RevisionSpec_tag(RevisionSpec):
468
 
    """To be implemented."""
469
 
 
470
 
    help_txt = """To be implemented."""
471
 
 
472
233
    prefix = 'tag:'
473
234
 
474
235
    def _match_on(self, branch, revs):
475
 
        raise errors.InvalidRevisionSpec(self.user_spec, branch,
476
 
                                         'tag: namespace registered,'
477
 
                                         ' but not implemented')
 
236
        raise BzrError('tag: namespace registered, but not implemented.')
478
237
 
479
238
SPEC_TYPES.append(RevisionSpec_tag)
480
239
 
481
240
 
482
 
class _RevListToTimestamps(object):
483
 
    """This takes a list of revisions, and allows you to bisect by date"""
484
 
 
485
 
    __slots__ = ['revs', 'branch']
486
 
 
487
 
    def __init__(self, revs, branch):
488
 
        self.revs = revs
489
 
        self.branch = branch
490
 
 
491
 
    def __getitem__(self, index):
492
 
        """Get the date of the index'd item"""
493
 
        r = self.branch.repository.get_revision(self.revs[index])
494
 
        # TODO: Handle timezone.
495
 
        return datetime.datetime.fromtimestamp(r.timestamp)
496
 
 
497
 
    def __len__(self):
498
 
        return len(self.revs)
499
 
 
500
 
 
501
241
class RevisionSpec_date(RevisionSpec):
502
 
    """Selects a revision on the basis of a datestamp."""
503
 
 
504
 
    help_txt = """Selects a revision on the basis of a datestamp.
505
 
 
506
 
    Supply a datestamp to select the first revision that matches the date.
507
 
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
508
 
    Matches the first entry after a given date (either at midnight or
509
 
    at a specified time).
510
 
 
511
 
    One way to display all the changes since yesterday would be:
512
 
        bzr log -r date:yesterday..-1
513
 
 
514
 
    examples:
515
 
      date:yesterday            -> select the first revision since yesterday
516
 
      date:2006-08-14,17:10:14  -> select the first revision after
517
 
                                   August 14th, 2006 at 5:10pm.
518
 
    """    
519
242
    prefix = 'date:'
520
243
    _date_re = re.compile(
521
244
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
524
247
        )
525
248
 
526
249
    def _match_on(self, branch, revs):
527
 
        """Spec for date revisions:
 
250
        """
 
251
        Spec for date revisions:
528
252
          date:value
529
253
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
530
254
          matches the first entry after a given date (either at midnight or
531
255
          at a specified time).
 
256
 
 
257
          So the proper way of saying 'give me all entries for today' is:
 
258
              -r date:today..date:tomorrow
532
259
        """
533
 
        #  XXX: This doesn't actually work
534
 
        #  So the proper way of saying 'give me all entries for today' is:
535
 
        #      -r date:yesterday..date:today
536
260
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
537
261
        if self.spec.lower() == 'yesterday':
538
262
            dt = today - datetime.timedelta(days=1)
543
267
        else:
544
268
            m = self._date_re.match(self.spec)
545
269
            if not m or (not m.group('date') and not m.group('time')):
546
 
                raise errors.InvalidRevisionSpec(self.user_spec,
547
 
                                                 branch, 'invalid date')
548
 
 
549
 
            try:
550
 
                if m.group('date'):
551
 
                    year = int(m.group('year'))
552
 
                    month = int(m.group('month'))
553
 
                    day = int(m.group('day'))
554
 
                else:
555
 
                    year = today.year
556
 
                    month = today.month
557
 
                    day = today.day
558
 
 
559
 
                if m.group('time'):
560
 
                    hour = int(m.group('hour'))
561
 
                    minute = int(m.group('minute'))
562
 
                    if m.group('second'):
563
 
                        second = int(m.group('second'))
564
 
                    else:
565
 
                        second = 0
566
 
                else:
567
 
                    hour, minute, second = 0,0,0
568
 
            except ValueError:
569
 
                raise errors.InvalidRevisionSpec(self.user_spec,
570
 
                                                 branch, 'invalid date')
 
270
                raise BzrError('Invalid revision date %r' % self.spec)
 
271
 
 
272
            if m.group('date'):
 
273
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
 
274
            else:
 
275
                year, month, day = today.year, today.month, today.day
 
276
            if m.group('time'):
 
277
                hour = int(m.group('hour'))
 
278
                minute = int(m.group('minute'))
 
279
                if m.group('second'):
 
280
                    second = int(m.group('second'))
 
281
                else:
 
282
                    second = 0
 
283
            else:
 
284
                hour, minute, second = 0,0,0
571
285
 
572
286
            dt = datetime.datetime(year=year, month=month, day=day,
573
287
                    hour=hour, minute=minute, second=second)
574
 
        branch.lock_read()
575
 
        try:
576
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
577
 
        finally:
578
 
            branch.unlock()
579
 
        if rev == len(revs):
580
 
            return RevisionInfo(branch, None)
581
 
        else:
582
 
            return RevisionInfo(branch, rev + 1)
 
288
        first = dt
 
289
        for i in range(len(revs)):
 
290
            r = branch.get_revision(revs[i])
 
291
            # TODO: Handle timezone.
 
292
            dt = datetime.datetime.fromtimestamp(r.timestamp)
 
293
            if first <= dt:
 
294
                return RevisionInfo(branch, i+1)
 
295
        return RevisionInfo(branch, None)
583
296
 
584
297
SPEC_TYPES.append(RevisionSpec_date)
585
298
 
586
299
 
587
300
class RevisionSpec_ancestor(RevisionSpec):
588
 
    """Selects a common ancestor with a second branch."""
589
 
 
590
 
    help_txt = """Selects a common ancestor with a second branch.
591
 
 
592
 
    Supply the path to a branch to select the common ancestor.
593
 
 
594
 
    The common ancestor is the last revision that existed in both
595
 
    branches. Usually this is the branch point, but it could also be
596
 
    a revision that was merged.
597
 
 
598
 
    This is frequently used with 'diff' to return all of the changes
599
 
    that your branch introduces, while excluding the changes that you
600
 
    have not merged from the remote branch.
601
 
 
602
 
    examples:
603
 
      ancestor:/path/to/branch
604
 
      $ bzr diff -r ancestor:../../mainline/branch
605
 
    """
606
301
    prefix = 'ancestor:'
607
302
 
608
303
    def _match_on(self, branch, revs):
609
 
        from bzrlib.branch import Branch
610
 
 
611
 
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
612
 
        other_branch = Branch.open(self.spec)
 
304
        from branch import Branch
 
305
        from revision import common_ancestor, MultipleRevisionSources
 
306
        other_branch = Branch.open_containing(self.spec)
613
307
        revision_a = branch.last_revision()
614
308
        revision_b = other_branch.last_revision()
615
309
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
616
 
            if r in (None, revision.NULL_REVISION):
617
 
                raise errors.NoCommits(b)
618
 
        revision_source = revision.MultipleRevisionSources(
619
 
                branch.repository, other_branch.repository)
620
 
        rev_id = revision.common_ancestor(revision_a, revision_b,
621
 
                                          revision_source)
 
310
            if r is None:
 
311
                raise NoCommits(b)
 
312
        revision_source = MultipleRevisionSources(branch, other_branch)
 
313
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
622
314
        try:
623
315
            revno = branch.revision_id_to_revno(rev_id)
624
 
        except errors.NoSuchRevision:
 
316
        except NoSuchRevision:
625
317
            revno = None
626
318
        return RevisionInfo(branch, revno, rev_id)
627
319
        
628
320
SPEC_TYPES.append(RevisionSpec_ancestor)
629
 
 
630
 
 
631
 
class RevisionSpec_branch(RevisionSpec):
632
 
    """Selects the last revision of a specified branch."""
633
 
 
634
 
    help_txt = """Selects the last revision of a specified branch.
635
 
 
636
 
    Supply the path to a branch to select its last revision.
637
 
 
638
 
    examples:
639
 
      branch:/path/to/branch
640
 
    """
641
 
    prefix = 'branch:'
642
 
 
643
 
    def _match_on(self, branch, revs):
644
 
        from bzrlib.branch import Branch
645
 
        other_branch = Branch.open(self.spec)
646
 
        revision_b = other_branch.last_revision()
647
 
        if revision_b in (None, revision.NULL_REVISION):
648
 
            raise errors.NoCommits(other_branch)
649
 
        # pull in the remote revisions so we can diff
650
 
        branch.fetch(other_branch, revision_b)
651
 
        try:
652
 
            revno = branch.revision_id_to_revno(revision_b)
653
 
        except errors.NoSuchRevision:
654
 
            revno = None
655
 
        return RevisionInfo(branch, revno, revision_b)
656
 
        
657
 
SPEC_TYPES.append(RevisionSpec_branch)