/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Martin Pool
  • Date: 2008-09-23 05:37:53 UTC
  • mfrom: (3331.3.13 lock_hooks)
  • mto: This revision was merged to the branch mainline in revision 3730.
  • Revision ID: mbp@sourcefrog.net-20080923053753-yusi3tdaemoflcya
Move Lock hooks onto a base Lock class and make them more consistent with other lock classes

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
import bisect
 
19
import datetime
 
20
import re
 
21
 
 
22
from bzrlib import (
 
23
    errors,
 
24
    osutils,
 
25
    revision,
 
26
    symbol_versioning,
 
27
    trace,
 
28
    tsort,
 
29
    )
 
30
 
 
31
 
 
32
_marker = []
 
33
 
 
34
 
 
35
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.
 
39
 
 
40
    An instance has two useful attributes: revno, and rev_id.
 
41
 
 
42
    They can also be accessed as spec[0] and spec[1] respectively,
 
43
    so that you can write code like:
 
44
    revno, rev_id = RevisionSpec(branch, spec)
 
45
    although this is probably going to be deprecated later.
 
46
 
 
47
    This class exists mostly to be the return value of a RevisionSpec,
 
48
    so that you can access the member you're interested in (number or id)
 
49
    or treat the result as a tuple.
 
50
    """
 
51
 
 
52
    def __init__(self, branch, revno, rev_id=_marker):
 
53
        self.branch = branch
 
54
        self.revno = revno
 
55
        if rev_id is _marker:
 
56
            # allow caller to be lazy
 
57
            if self.revno is None:
 
58
                self.rev_id = None
 
59
            else:
 
60
                self.rev_id = branch.get_rev_id(self.revno)
 
61
        else:
 
62
            self.rev_id = rev_id
 
63
 
 
64
    def __nonzero__(self):
 
65
        # first the easy ones...
 
66
        if self.rev_id is None:
 
67
            return False
 
68
        if self.revno is not None:
 
69
            return True
 
70
        # TODO: otherwise, it should depend on how I was built -
 
71
        # if it's in_history(branch), then check revision_history(),
 
72
        # if it's in_store(branch), do the check below
 
73
        return self.branch.repository.has_revision(self.rev_id)
 
74
 
 
75
    def __len__(self):
 
76
        return 2
 
77
 
 
78
    def __getitem__(self, index):
 
79
        if index == 0: return self.revno
 
80
        if index == 1: return self.rev_id
 
81
        raise IndexError(index)
 
82
 
 
83
    def get(self):
 
84
        return self.branch.repository.get_revision(self.rev_id)
 
85
 
 
86
    def __eq__(self, other):
 
87
        if type(other) not in (tuple, list, type(self)):
 
88
            return False
 
89
        if type(other) is type(self) and self.branch is not other.branch:
 
90
            return False
 
91
        return tuple(self) == tuple(other)
 
92
 
 
93
    def __repr__(self):
 
94
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
 
95
            self.revno, self.rev_id, self.branch)
 
96
 
 
97
    @staticmethod
 
98
    def from_revision_id(branch, revision_id, revs):
 
99
        """Construct a RevisionInfo given just the id.
 
100
 
 
101
        Use this if you don't know or care what the revno is.
 
102
        """
 
103
        if revision_id == revision.NULL_REVISION:
 
104
            return RevisionInfo(branch, 0, revision_id)
 
105
        try:
 
106
            revno = revs.index(revision_id) + 1
 
107
        except ValueError:
 
108
            revno = None
 
109
        return RevisionInfo(branch, revno, revision_id)
 
110
 
 
111
 
 
112
# classes in this list should have a "prefix" attribute, against which
 
113
# string specs are matched
 
114
SPEC_TYPES = []
 
115
_revno_regex = None
 
116
 
 
117
 
 
118
class RevisionSpec(object):
 
119
    """A parsed revision specification."""
 
120
 
 
121
    help_txt = """A parsed revision specification.
 
122
 
 
123
    A revision specification can be an integer, in which case it is
 
124
    assumed to be a revno (though this will translate negative values
 
125
    into positive ones); or it can be a string, in which case it is
 
126
    parsed for something like 'date:' or 'revid:' etc.
 
127
 
 
128
    Revision specs are an UI element, and they have been moved out
 
129
    of the branch class to leave "back-end" classes unaware of such
 
130
    details.  Code that gets a revno or rev_id from other code should
 
131
    not be using revision specs - revnos and revision ids are the
 
132
    accepted ways to refer to revisions internally.
 
133
 
 
134
    (Equivalent to the old Branch method get_revision_info())
 
135
    """
 
136
 
 
137
    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.
 
158
        """
 
159
        if not isinstance(spec, (type(None), basestring)):
 
160
            raise TypeError('error')
 
161
 
 
162
        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)
 
169
        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
 
197
        if self.prefix and spec.startswith(self.prefix):
 
198
            spec = spec[len(self.prefix):]
 
199
        self.spec = spec
 
200
 
 
201
    def _match_on(self, branch, revs):
 
202
        trace.mutter('Returning RevisionSpec._match_on: None')
 
203
        return RevisionInfo(branch, None, None)
 
204
 
 
205
    def _match_on_and_check(self, branch, revs):
 
206
        info = self._match_on(branch, revs)
 
207
        if info:
 
208
            return info
 
209
        elif info == (None, None):
 
210
            # special case - nothing supplied
 
211
            return info
 
212
        elif self.prefix:
 
213
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
214
        else:
 
215
            raise errors.InvalidRevisionSpec(self.spec, branch)
 
216
 
 
217
    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
 
227
        return self._match_on_and_check(branch, revs)
 
228
 
 
229
        # FIXME: in_history is somewhat broken,
 
230
        # it will return non-history revisions in many
 
231
        # circumstances. The expected facility is that
 
232
        # in_history only returns revision-history revs,
 
233
        # in_store returns any rev. RBC 20051010
 
234
    # aliases for now, when we fix the core logic, then they
 
235
    # will do what you expect.
 
236
    in_store = in_history
 
237
    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
 
 
255
    def __repr__(self):
 
256
        # 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
 
273
 
 
274
 
 
275
# private API
 
276
 
 
277
class RevisionSpec_revno(RevisionSpec):
 
278
    """Selects a revision using a number."""
 
279
 
 
280
    help_txt = """Selects a revision using a number.
 
281
 
 
282
    Use an integer to specify a revision in the history of the branch.
 
283
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
284
    A negative number will count from the end of the branch (-1 is the
 
285
    last revision, -2 the previous one). If the negative number is larger
 
286
    than the branch's history, the first revision is returned.
 
287
    Examples::
 
288
 
 
289
      revno:1                   -> return the first revision of this branch
 
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
    prefix = 'revno:'
 
299
    wants_revision_history = False
 
300
 
 
301
    def _match_on(self, branch, revs):
 
302
        """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
 
389
 
 
390
SPEC_TYPES.append(RevisionSpec_revno)
 
391
 
 
392
 
 
393
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
    prefix = 'revid:'
 
407
 
 
408
    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)
 
417
 
 
418
SPEC_TYPES.append(RevisionSpec_revid)
 
419
 
 
420
 
 
421
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
 
 
434
    prefix = 'last:'
 
435
 
 
436
    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
        try:
 
449
            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
 
469
 
 
470
SPEC_TYPES.append(RevisionSpec_last)
 
471
 
 
472
 
 
473
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.  This is
 
479
    mostly useful when inspecting revisions that are not in the revision history
 
480
    of a branch.
 
481
 
 
482
    It is an error to request the parent of the null revision (before:0).
 
483
 
 
484
    Examples::
 
485
 
 
486
      before:1913    -> Return the parent of revno 1913 (revno 1912)
 
487
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
 
488
                                            aaaa@bbbb-1234567890
 
489
      bzr diff -r before:1913..1913
 
490
            -> Find the changes between revision 1913 and its parent (1912).
 
491
               (What changes did revision 1913 introduce).
 
492
               This is equivalent to:  bzr diff -c 1913
 
493
    """
 
494
 
 
495
    prefix = 'before:'
 
496
    
 
497
    def _match_on(self, branch, revs):
 
498
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
 
499
        if r.revno == 0:
 
500
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
501
                                         'cannot go before the null: revision')
 
502
        if r.revno is None:
 
503
            # We need to use the repository history here
 
504
            rev = branch.repository.get_revision(r.rev_id)
 
505
            if not rev.parent_ids:
 
506
                revno = 0
 
507
                revision_id = revision.NULL_REVISION
 
508
            else:
 
509
                revision_id = rev.parent_ids[0]
 
510
                try:
 
511
                    revno = revs.index(revision_id) + 1
 
512
                except ValueError:
 
513
                    revno = None
 
514
        else:
 
515
            revno = r.revno - 1
 
516
            try:
 
517
                revision_id = branch.get_rev_id(revno, revs)
 
518
            except errors.NoSuchRevision:
 
519
                raise errors.InvalidRevisionSpec(self.user_spec,
 
520
                                                 branch)
 
521
        return RevisionInfo(branch, revno, revision_id)
 
522
 
 
523
    def _as_revision_id(self, context_branch):
 
524
        base_revspec = RevisionSpec.from_string(self.spec)
 
525
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
526
        if base_revision_id == revision.NULL_REVISION:
 
527
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
528
                                         'cannot go before the null: revision')
 
529
        context_repo = context_branch.repository
 
530
        context_repo.lock_read()
 
531
        try:
 
532
            parent_map = context_repo.get_parent_map([base_revision_id])
 
533
        finally:
 
534
            context_repo.unlock()
 
535
        if base_revision_id not in parent_map:
 
536
            # Ghost, or unknown revision id
 
537
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
538
                'cannot find the matching revision')
 
539
        parents = parent_map[base_revision_id]
 
540
        if len(parents) < 1:
 
541
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
542
                'No parents for revision.')
 
543
        return parents[0]
 
544
 
 
545
SPEC_TYPES.append(RevisionSpec_before)
 
546
 
 
547
 
 
548
class RevisionSpec_tag(RevisionSpec):
 
549
    """Select a revision identified by tag name"""
 
550
 
 
551
    help_txt = """Selects a revision identified by a tag name.
 
552
 
 
553
    Tags are stored in the branch and created by the 'tag' command.
 
554
    """
 
555
 
 
556
    prefix = 'tag:'
 
557
 
 
558
    def _match_on(self, branch, revs):
 
559
        # Can raise tags not supported, NoSuchTag, etc
 
560
        return RevisionInfo.from_revision_id(branch,
 
561
            branch.tags.lookup_tag(self.spec),
 
562
            revs)
 
563
 
 
564
    def _as_revision_id(self, context_branch):
 
565
        return context_branch.tags.lookup_tag(self.spec)
 
566
 
 
567
SPEC_TYPES.append(RevisionSpec_tag)
 
568
 
 
569
 
 
570
class _RevListToTimestamps(object):
 
571
    """This takes a list of revisions, and allows you to bisect by date"""
 
572
 
 
573
    __slots__ = ['revs', 'branch']
 
574
 
 
575
    def __init__(self, revs, branch):
 
576
        self.revs = revs
 
577
        self.branch = branch
 
578
 
 
579
    def __getitem__(self, index):
 
580
        """Get the date of the index'd item"""
 
581
        r = self.branch.repository.get_revision(self.revs[index])
 
582
        # TODO: Handle timezone.
 
583
        return datetime.datetime.fromtimestamp(r.timestamp)
 
584
 
 
585
    def __len__(self):
 
586
        return len(self.revs)
 
587
 
 
588
 
 
589
class RevisionSpec_date(RevisionSpec):
 
590
    """Selects a revision on the basis of a datestamp."""
 
591
 
 
592
    help_txt = """Selects a revision on the basis of a datestamp.
 
593
 
 
594
    Supply a datestamp to select the first revision that matches the date.
 
595
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
596
    Matches the first entry after a given date (either at midnight or
 
597
    at a specified time).
 
598
 
 
599
    One way to display all the changes since yesterday would be::
 
600
 
 
601
        bzr log -r date:yesterday..
 
602
 
 
603
    Examples::
 
604
 
 
605
      date:yesterday            -> select the first revision since yesterday
 
606
      date:2006-08-14,17:10:14  -> select the first revision after
 
607
                                   August 14th, 2006 at 5:10pm.
 
608
    """    
 
609
    prefix = 'date:'
 
610
    _date_re = re.compile(
 
611
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
612
            r'(,|T)?\s*'
 
613
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
614
        )
 
615
 
 
616
    def _match_on(self, branch, revs):
 
617
        """Spec for date revisions:
 
618
          date:value
 
619
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
620
          matches the first entry after a given date (either at midnight or
 
621
          at a specified time).
 
622
        """
 
623
        #  XXX: This doesn't actually work
 
624
        #  So the proper way of saying 'give me all entries for today' is:
 
625
        #      -r date:yesterday..date:today
 
626
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
 
627
        if self.spec.lower() == 'yesterday':
 
628
            dt = today - datetime.timedelta(days=1)
 
629
        elif self.spec.lower() == 'today':
 
630
            dt = today
 
631
        elif self.spec.lower() == 'tomorrow':
 
632
            dt = today + datetime.timedelta(days=1)
 
633
        else:
 
634
            m = self._date_re.match(self.spec)
 
635
            if not m or (not m.group('date') and not m.group('time')):
 
636
                raise errors.InvalidRevisionSpec(self.user_spec,
 
637
                                                 branch, 'invalid date')
 
638
 
 
639
            try:
 
640
                if m.group('date'):
 
641
                    year = int(m.group('year'))
 
642
                    month = int(m.group('month'))
 
643
                    day = int(m.group('day'))
 
644
                else:
 
645
                    year = today.year
 
646
                    month = today.month
 
647
                    day = today.day
 
648
 
 
649
                if m.group('time'):
 
650
                    hour = int(m.group('hour'))
 
651
                    minute = int(m.group('minute'))
 
652
                    if m.group('second'):
 
653
                        second = int(m.group('second'))
 
654
                    else:
 
655
                        second = 0
 
656
                else:
 
657
                    hour, minute, second = 0,0,0
 
658
            except ValueError:
 
659
                raise errors.InvalidRevisionSpec(self.user_spec,
 
660
                                                 branch, 'invalid date')
 
661
 
 
662
            dt = datetime.datetime(year=year, month=month, day=day,
 
663
                    hour=hour, minute=minute, second=second)
 
664
        branch.lock_read()
 
665
        try:
 
666
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
667
        finally:
 
668
            branch.unlock()
 
669
        if rev == len(revs):
 
670
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
671
        else:
 
672
            return RevisionInfo(branch, rev + 1)
 
673
 
 
674
SPEC_TYPES.append(RevisionSpec_date)
 
675
 
 
676
 
 
677
class RevisionSpec_ancestor(RevisionSpec):
 
678
    """Selects a common ancestor with a second branch."""
 
679
 
 
680
    help_txt = """Selects a common ancestor with a second branch.
 
681
 
 
682
    Supply the path to a branch to select the common ancestor.
 
683
 
 
684
    The common ancestor is the last revision that existed in both
 
685
    branches. Usually this is the branch point, but it could also be
 
686
    a revision that was merged.
 
687
 
 
688
    This is frequently used with 'diff' to return all of the changes
 
689
    that your branch introduces, while excluding the changes that you
 
690
    have not merged from the remote branch.
 
691
 
 
692
    Examples::
 
693
 
 
694
      ancestor:/path/to/branch
 
695
      $ bzr diff -r ancestor:../../mainline/branch
 
696
    """
 
697
    prefix = 'ancestor:'
 
698
 
 
699
    def _match_on(self, branch, revs):
 
700
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
701
        return self._find_revision_info(branch, self.spec)
 
702
 
 
703
    def _as_revision_id(self, context_branch):
 
704
        return self._find_revision_id(context_branch, self.spec)
 
705
 
 
706
    @staticmethod
 
707
    def _find_revision_info(branch, other_location):
 
708
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
 
709
                                                              other_location)
 
710
        try:
 
711
            revno = branch.revision_id_to_revno(revision_id)
 
712
        except errors.NoSuchRevision:
 
713
            revno = None
 
714
        return RevisionInfo(branch, revno, revision_id)
 
715
 
 
716
    @staticmethod
 
717
    def _find_revision_id(branch, other_location):
 
718
        from bzrlib.branch import Branch
 
719
 
 
720
        branch.lock_read()
 
721
        try:
 
722
            revision_a = revision.ensure_null(branch.last_revision())
 
723
            if revision_a == revision.NULL_REVISION:
 
724
                raise errors.NoCommits(branch)
 
725
            other_branch = Branch.open(other_location)
 
726
            other_branch.lock_read()
 
727
            try:
 
728
                revision_b = revision.ensure_null(other_branch.last_revision())
 
729
                if revision_b == revision.NULL_REVISION:
 
730
                    raise errors.NoCommits(other_branch)
 
731
                graph = branch.repository.get_graph(other_branch.repository)
 
732
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
733
            finally:
 
734
                other_branch.unlock()
 
735
            if rev_id == revision.NULL_REVISION:
 
736
                raise errors.NoCommonAncestor(revision_a, revision_b)
 
737
            return rev_id
 
738
        finally:
 
739
            branch.unlock()
 
740
 
 
741
 
 
742
SPEC_TYPES.append(RevisionSpec_ancestor)
 
743
 
 
744
 
 
745
class RevisionSpec_branch(RevisionSpec):
 
746
    """Selects the last revision of a specified branch."""
 
747
 
 
748
    help_txt = """Selects the last revision of a specified branch.
 
749
 
 
750
    Supply the path to a branch to select its last revision.
 
751
 
 
752
    Examples::
 
753
 
 
754
      branch:/path/to/branch
 
755
    """
 
756
    prefix = 'branch:'
 
757
 
 
758
    def _match_on(self, branch, revs):
 
759
        from bzrlib.branch import Branch
 
760
        other_branch = Branch.open(self.spec)
 
761
        revision_b = other_branch.last_revision()
 
762
        if revision_b in (None, revision.NULL_REVISION):
 
763
            raise errors.NoCommits(other_branch)
 
764
        # pull in the remote revisions so we can diff
 
765
        branch.fetch(other_branch, revision_b)
 
766
        try:
 
767
            revno = branch.revision_id_to_revno(revision_b)
 
768
        except errors.NoSuchRevision:
 
769
            revno = None
 
770
        return RevisionInfo(branch, revno, revision_b)
 
771
 
 
772
    def _as_revision_id(self, context_branch):
 
773
        from bzrlib.branch import Branch
 
774
        other_branch = Branch.open(self.spec)
 
775
        last_revision = other_branch.last_revision()
 
776
        last_revision = revision.ensure_null(last_revision)
 
777
        context_branch.fetch(other_branch, last_revision)
 
778
        if last_revision == revision.NULL_REVISION:
 
779
            raise errors.NoCommits(other_branch)
 
780
        return last_revision
 
781
 
 
782
SPEC_TYPES.append(RevisionSpec_branch)
 
783
 
 
784
 
 
785
class RevisionSpec_submit(RevisionSpec_ancestor):
 
786
    """Selects a common ancestor with a submit branch."""
 
787
 
 
788
    help_txt = """Selects a common ancestor with the submit branch.
 
789
 
 
790
    Diffing against this shows all the changes that were made in this branch,
 
791
    and is a good predictor of what merge will do.  The submit branch is
 
792
    used by the bundle and merge directive commands.  If no submit branch
 
793
    is specified, the parent branch is used instead.
 
794
 
 
795
    The common ancestor is the last revision that existed in both
 
796
    branches. Usually this is the branch point, but it could also be
 
797
    a revision that was merged.
 
798
 
 
799
    Examples::
 
800
 
 
801
      $ bzr diff -r submit:
 
802
    """
 
803
 
 
804
    prefix = 'submit:'
 
805
 
 
806
    def _get_submit_location(self, branch):
 
807
        submit_location = branch.get_submit_branch()
 
808
        location_type = 'submit branch'
 
809
        if submit_location is None:
 
810
            submit_location = branch.get_parent()
 
811
            location_type = 'parent branch'
 
812
        if submit_location is None:
 
813
            raise errors.NoSubmitBranch(branch)
 
814
        trace.note('Using %s %s', location_type, submit_location)
 
815
        return submit_location
 
816
 
 
817
    def _match_on(self, branch, revs):
 
818
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
819
        return self._find_revision_info(branch,
 
820
            self._get_submit_location(branch))
 
821
 
 
822
    def _as_revision_id(self, context_branch):
 
823
        return self._find_revision_id(context_branch,
 
824
            self._get_submit_location(context_branch))
 
825
 
 
826
 
 
827
SPEC_TYPES.append(RevisionSpec_submit)