/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: Lukáš Lalinský
  • Date: 2008-08-28 13:41:15 UTC
  • mto: (3732.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3733.
  • Revision ID: lalinsky@gmail.com-20080828134115-265uyumclq5qvetg
Fix `bzr st -rbranch:PATH_TO_BRANCH`

* Add RevisionSpec.as_tree which returns a tree representation of the revision specifier. This might return a remote revision tree.
* Make status use this new method and not require RevisionSpec.as_revision_id, which for RevisionSpec_branch fetches data to the local repository.
* Refactor common code for getting either a revision tree or a tree/branch's basis tree into a private function _get_revision_tree and make it use RevisionSpec.as_tree.

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 as_tree(self, context_branch):
 
256
        """Return the tree object for this revisions spec.
 
257
 
 
258
        Some revision specs require a context_branch to be able to determine
 
259
        the revision id and access the repository. Not all specs will make
 
260
        use of it.
 
261
        """
 
262
        return self._as_tree(context_branch)
 
263
 
 
264
    def _as_tree(self, context_branch):
 
265
        """Implementation of as_tree()
 
266
 
 
267
        Classes should override this function to provide appropriate
 
268
        functionality. The default is to just call '.as_revision_id()'
 
269
        and get the revision tree from context_branch's repository.
 
270
        """
 
271
        revision_id = self.as_revision_id(context_branch)
 
272
        return context_branch.repository.revision_tree(revision_id)
 
273
 
 
274
    def __repr__(self):
 
275
        # this is mostly for helping with testing
 
276
        return '<%s %s>' % (self.__class__.__name__,
 
277
                              self.user_spec)
 
278
    
 
279
    def needs_branch(self):
 
280
        """Whether this revision spec needs a branch.
 
281
 
 
282
        Set this to False the branch argument of _match_on is not used.
 
283
        """
 
284
        return True
 
285
 
 
286
    def get_branch(self):
 
287
        """When the revision specifier contains a branch location, return it.
 
288
        
 
289
        Otherwise, return None.
 
290
        """
 
291
        return None
 
292
 
 
293
 
 
294
# private API
 
295
 
 
296
class RevisionSpec_revno(RevisionSpec):
 
297
    """Selects a revision using a number."""
 
298
 
 
299
    help_txt = """Selects a revision using a number.
 
300
 
 
301
    Use an integer to specify a revision in the history of the branch.
 
302
    Optionally a branch can be specified. The 'revno:' prefix is optional.
 
303
    A negative number will count from the end of the branch (-1 is the
 
304
    last revision, -2 the previous one). If the negative number is larger
 
305
    than the branch's history, the first revision is returned.
 
306
    Examples::
 
307
 
 
308
      revno:1                   -> return the first revision
 
309
      revno:3:/path/to/branch   -> return the 3rd revision of
 
310
                                   the branch '/path/to/branch'
 
311
      revno:-1                  -> The last revision in a branch.
 
312
      -2:http://other/branch    -> The second to last revision in the
 
313
                                   remote branch.
 
314
      -1000000                  -> Most likely the first revision, unless
 
315
                                   your history is very long.
 
316
    """
 
317
    prefix = 'revno:'
 
318
    wants_revision_history = False
 
319
 
 
320
    def _match_on(self, branch, revs):
 
321
        """Lookup a revision by revision number"""
 
322
        branch, revno, revision_id = self._lookup(branch, revs)
 
323
        return RevisionInfo(branch, revno, revision_id)
 
324
 
 
325
    def _lookup(self, branch, revs_or_none):
 
326
        loc = self.spec.find(':')
 
327
        if loc == -1:
 
328
            revno_spec = self.spec
 
329
            branch_spec = None
 
330
        else:
 
331
            revno_spec = self.spec[:loc]
 
332
            branch_spec = self.spec[loc+1:]
 
333
 
 
334
        if revno_spec == '':
 
335
            if not branch_spec:
 
336
                raise errors.InvalidRevisionSpec(self.user_spec,
 
337
                        branch, 'cannot have an empty revno and no branch')
 
338
            revno = None
 
339
        else:
 
340
            try:
 
341
                revno = int(revno_spec)
 
342
                dotted = False
 
343
            except ValueError:
 
344
                # dotted decimal. This arguably should not be here
 
345
                # but the from_string method is a little primitive 
 
346
                # right now - RBC 20060928
 
347
                try:
 
348
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
 
349
                except ValueError, e:
 
350
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
351
 
 
352
                dotted = True
 
353
 
 
354
        if branch_spec:
 
355
            # the user has override the branch to look in.
 
356
            # we need to refresh the revision_history map and
 
357
            # the branch object.
 
358
            from bzrlib.branch import Branch
 
359
            branch = Branch.open(branch_spec)
 
360
            revs_or_none = None
 
361
 
 
362
        if dotted:
 
363
            branch.lock_read()
 
364
            try:
 
365
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
 
366
                revisions = [revision_id for revision_id, revno
 
367
                             in revision_id_to_revno.iteritems()
 
368
                             if revno == match_revno]
 
369
            finally:
 
370
                branch.unlock()
 
371
            if len(revisions) != 1:
 
372
                return branch, None, None
 
373
            else:
 
374
                # there is no traditional 'revno' for dotted-decimal revnos.
 
375
                # so for  API compatability we return None.
 
376
                return branch, None, revisions[0]
 
377
        else:
 
378
            last_revno, last_revision_id = branch.last_revision_info()
 
379
            if revno < 0:
 
380
                # if get_rev_id supported negative revnos, there would not be a
 
381
                # need for this special case.
 
382
                if (-revno) >= last_revno:
 
383
                    revno = 1
 
384
                else:
 
385
                    revno = last_revno + revno + 1
 
386
            try:
 
387
                revision_id = branch.get_rev_id(revno, revs_or_none)
 
388
            except errors.NoSuchRevision:
 
389
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
390
        return branch, revno, revision_id
 
391
 
 
392
    def _as_revision_id(self, context_branch):
 
393
        # We would have the revno here, but we don't really care
 
394
        branch, revno, revision_id = self._lookup(context_branch, None)
 
395
        return revision_id
 
396
 
 
397
    def needs_branch(self):
 
398
        return self.spec.find(':') == -1
 
399
 
 
400
    def get_branch(self):
 
401
        if self.spec.find(':') == -1:
 
402
            return None
 
403
        else:
 
404
            return self.spec[self.spec.find(':')+1:]
 
405
 
 
406
# Old compatibility 
 
407
RevisionSpec_int = RevisionSpec_revno
 
408
 
 
409
SPEC_TYPES.append(RevisionSpec_revno)
 
410
 
 
411
 
 
412
class RevisionSpec_revid(RevisionSpec):
 
413
    """Selects a revision using the revision id."""
 
414
 
 
415
    help_txt = """Selects a revision using the revision id.
 
416
 
 
417
    Supply a specific revision id, that can be used to specify any
 
418
    revision id in the ancestry of the branch. 
 
419
    Including merges, and pending merges.
 
420
    Examples::
 
421
 
 
422
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
 
423
    """
 
424
 
 
425
    prefix = 'revid:'
 
426
 
 
427
    def _match_on(self, branch, revs):
 
428
        # self.spec comes straight from parsing the command line arguments,
 
429
        # so we expect it to be a Unicode string. Switch it to the internal
 
430
        # representation.
 
431
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
 
432
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
 
433
 
 
434
    def _as_revision_id(self, context_branch):
 
435
        return osutils.safe_revision_id(self.spec, warn=False)
 
436
 
 
437
SPEC_TYPES.append(RevisionSpec_revid)
 
438
 
 
439
 
 
440
class RevisionSpec_last(RevisionSpec):
 
441
    """Selects the nth revision from the end."""
 
442
 
 
443
    help_txt = """Selects the nth revision from the end.
 
444
 
 
445
    Supply a positive number to get the nth revision from the end.
 
446
    This is the same as supplying negative numbers to the 'revno:' spec.
 
447
    Examples::
 
448
 
 
449
      last:1        -> return the last revision
 
450
      last:3        -> return the revision 2 before the end.
 
451
    """
 
452
 
 
453
    prefix = 'last:'
 
454
 
 
455
    def _match_on(self, branch, revs):
 
456
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
457
        return RevisionInfo(branch, revno, revision_id)
 
458
 
 
459
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
460
        last_revno, last_revision_id = context_branch.last_revision_info()
 
461
 
 
462
        if self.spec == '':
 
463
            if not last_revno:
 
464
                raise errors.NoCommits(context_branch)
 
465
            return last_revno, last_revision_id
 
466
 
 
467
        try:
 
468
            offset = int(self.spec)
 
469
        except ValueError, e:
 
470
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
 
471
 
 
472
        if offset <= 0:
 
473
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
474
                                             'you must supply a positive value')
 
475
 
 
476
        revno = last_revno - offset + 1
 
477
        try:
 
478
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
 
479
        except errors.NoSuchRevision:
 
480
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
481
        return revno, revision_id
 
482
 
 
483
    def _as_revision_id(self, context_branch):
 
484
        # We compute the revno as part of the process, but we don't really care
 
485
        # about it.
 
486
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
487
        return revision_id
 
488
 
 
489
SPEC_TYPES.append(RevisionSpec_last)
 
490
 
 
491
 
 
492
class RevisionSpec_before(RevisionSpec):
 
493
    """Selects the parent of the revision specified."""
 
494
 
 
495
    help_txt = """Selects the parent of the revision specified.
 
496
 
 
497
    Supply any revision spec to return the parent of that revision.
 
498
    It is an error to request the parent of the null revision (before:0).
 
499
    This is mostly useful when inspecting revisions that are not in the
 
500
    revision history of a branch.
 
501
 
 
502
    Examples::
 
503
 
 
504
      before:1913    -> Return the parent of revno 1913 (revno 1912)
 
505
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
 
506
                                            aaaa@bbbb-1234567890
 
507
      bzr diff -r before:revid:aaaa..revid:aaaa
 
508
            -> Find the changes between revision 'aaaa' and its parent.
 
509
               (what changes did 'aaaa' introduce)
 
510
    """
 
511
 
 
512
    prefix = 'before:'
 
513
    
 
514
    def _match_on(self, branch, revs):
 
515
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
 
516
        if r.revno == 0:
 
517
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
 
518
                                         'cannot go before the null: revision')
 
519
        if r.revno is None:
 
520
            # We need to use the repository history here
 
521
            rev = branch.repository.get_revision(r.rev_id)
 
522
            if not rev.parent_ids:
 
523
                revno = 0
 
524
                revision_id = revision.NULL_REVISION
 
525
            else:
 
526
                revision_id = rev.parent_ids[0]
 
527
                try:
 
528
                    revno = revs.index(revision_id) + 1
 
529
                except ValueError:
 
530
                    revno = None
 
531
        else:
 
532
            revno = r.revno - 1
 
533
            try:
 
534
                revision_id = branch.get_rev_id(revno, revs)
 
535
            except errors.NoSuchRevision:
 
536
                raise errors.InvalidRevisionSpec(self.user_spec,
 
537
                                                 branch)
 
538
        return RevisionInfo(branch, revno, revision_id)
 
539
 
 
540
    def _as_revision_id(self, context_branch):
 
541
        base_revspec = RevisionSpec.from_string(self.spec)
 
542
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
543
        if base_revision_id == revision.NULL_REVISION:
 
544
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
545
                                         'cannot go before the null: revision')
 
546
        context_repo = context_branch.repository
 
547
        context_repo.lock_read()
 
548
        try:
 
549
            parent_map = context_repo.get_parent_map([base_revision_id])
 
550
        finally:
 
551
            context_repo.unlock()
 
552
        if base_revision_id not in parent_map:
 
553
            # Ghost, or unknown revision id
 
554
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
555
                'cannot find the matching revision')
 
556
        parents = parent_map[base_revision_id]
 
557
        if len(parents) < 1:
 
558
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
559
                'No parents for revision.')
 
560
        return parents[0]
 
561
 
 
562
SPEC_TYPES.append(RevisionSpec_before)
 
563
 
 
564
 
 
565
class RevisionSpec_tag(RevisionSpec):
 
566
    """Select a revision identified by tag name"""
 
567
 
 
568
    help_txt = """Selects a revision identified by a tag name.
 
569
 
 
570
    Tags are stored in the branch and created by the 'tag' command.
 
571
    """
 
572
 
 
573
    prefix = 'tag:'
 
574
 
 
575
    def _match_on(self, branch, revs):
 
576
        # Can raise tags not supported, NoSuchTag, etc
 
577
        return RevisionInfo.from_revision_id(branch,
 
578
            branch.tags.lookup_tag(self.spec),
 
579
            revs)
 
580
 
 
581
    def _as_revision_id(self, context_branch):
 
582
        return context_branch.tags.lookup_tag(self.spec)
 
583
 
 
584
SPEC_TYPES.append(RevisionSpec_tag)
 
585
 
 
586
 
 
587
class _RevListToTimestamps(object):
 
588
    """This takes a list of revisions, and allows you to bisect by date"""
 
589
 
 
590
    __slots__ = ['revs', 'branch']
 
591
 
 
592
    def __init__(self, revs, branch):
 
593
        self.revs = revs
 
594
        self.branch = branch
 
595
 
 
596
    def __getitem__(self, index):
 
597
        """Get the date of the index'd item"""
 
598
        r = self.branch.repository.get_revision(self.revs[index])
 
599
        # TODO: Handle timezone.
 
600
        return datetime.datetime.fromtimestamp(r.timestamp)
 
601
 
 
602
    def __len__(self):
 
603
        return len(self.revs)
 
604
 
 
605
 
 
606
class RevisionSpec_date(RevisionSpec):
 
607
    """Selects a revision on the basis of a datestamp."""
 
608
 
 
609
    help_txt = """Selects a revision on the basis of a datestamp.
 
610
 
 
611
    Supply a datestamp to select the first revision that matches the date.
 
612
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
613
    Matches the first entry after a given date (either at midnight or
 
614
    at a specified time).
 
615
 
 
616
    One way to display all the changes since yesterday would be::
 
617
 
 
618
        bzr log -r date:yesterday..
 
619
 
 
620
    Examples::
 
621
 
 
622
      date:yesterday            -> select the first revision since yesterday
 
623
      date:2006-08-14,17:10:14  -> select the first revision after
 
624
                                   August 14th, 2006 at 5:10pm.
 
625
    """    
 
626
    prefix = 'date:'
 
627
    _date_re = re.compile(
 
628
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
629
            r'(,|T)?\s*'
 
630
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
631
        )
 
632
 
 
633
    def _match_on(self, branch, revs):
 
634
        """Spec for date revisions:
 
635
          date:value
 
636
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
637
          matches the first entry after a given date (either at midnight or
 
638
          at a specified time).
 
639
        """
 
640
        #  XXX: This doesn't actually work
 
641
        #  So the proper way of saying 'give me all entries for today' is:
 
642
        #      -r date:yesterday..date:today
 
643
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
 
644
        if self.spec.lower() == 'yesterday':
 
645
            dt = today - datetime.timedelta(days=1)
 
646
        elif self.spec.lower() == 'today':
 
647
            dt = today
 
648
        elif self.spec.lower() == 'tomorrow':
 
649
            dt = today + datetime.timedelta(days=1)
 
650
        else:
 
651
            m = self._date_re.match(self.spec)
 
652
            if not m or (not m.group('date') and not m.group('time')):
 
653
                raise errors.InvalidRevisionSpec(self.user_spec,
 
654
                                                 branch, 'invalid date')
 
655
 
 
656
            try:
 
657
                if m.group('date'):
 
658
                    year = int(m.group('year'))
 
659
                    month = int(m.group('month'))
 
660
                    day = int(m.group('day'))
 
661
                else:
 
662
                    year = today.year
 
663
                    month = today.month
 
664
                    day = today.day
 
665
 
 
666
                if m.group('time'):
 
667
                    hour = int(m.group('hour'))
 
668
                    minute = int(m.group('minute'))
 
669
                    if m.group('second'):
 
670
                        second = int(m.group('second'))
 
671
                    else:
 
672
                        second = 0
 
673
                else:
 
674
                    hour, minute, second = 0,0,0
 
675
            except ValueError:
 
676
                raise errors.InvalidRevisionSpec(self.user_spec,
 
677
                                                 branch, 'invalid date')
 
678
 
 
679
            dt = datetime.datetime(year=year, month=month, day=day,
 
680
                    hour=hour, minute=minute, second=second)
 
681
        branch.lock_read()
 
682
        try:
 
683
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
 
684
        finally:
 
685
            branch.unlock()
 
686
        if rev == len(revs):
 
687
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
688
        else:
 
689
            return RevisionInfo(branch, rev + 1)
 
690
 
 
691
SPEC_TYPES.append(RevisionSpec_date)
 
692
 
 
693
 
 
694
class RevisionSpec_ancestor(RevisionSpec):
 
695
    """Selects a common ancestor with a second branch."""
 
696
 
 
697
    help_txt = """Selects a common ancestor with a second branch.
 
698
 
 
699
    Supply the path to a branch to select the common ancestor.
 
700
 
 
701
    The common ancestor is the last revision that existed in both
 
702
    branches. Usually this is the branch point, but it could also be
 
703
    a revision that was merged.
 
704
 
 
705
    This is frequently used with 'diff' to return all of the changes
 
706
    that your branch introduces, while excluding the changes that you
 
707
    have not merged from the remote branch.
 
708
 
 
709
    Examples::
 
710
 
 
711
      ancestor:/path/to/branch
 
712
      $ bzr diff -r ancestor:../../mainline/branch
 
713
    """
 
714
    prefix = 'ancestor:'
 
715
 
 
716
    def _match_on(self, branch, revs):
 
717
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
718
        return self._find_revision_info(branch, self.spec)
 
719
 
 
720
    def _as_revision_id(self, context_branch):
 
721
        return self._find_revision_id(context_branch, self.spec)
 
722
 
 
723
    @staticmethod
 
724
    def _find_revision_info(branch, other_location):
 
725
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
 
726
                                                              other_location)
 
727
        try:
 
728
            revno = branch.revision_id_to_revno(revision_id)
 
729
        except errors.NoSuchRevision:
 
730
            revno = None
 
731
        return RevisionInfo(branch, revno, revision_id)
 
732
 
 
733
    @staticmethod
 
734
    def _find_revision_id(branch, other_location):
 
735
        from bzrlib.branch import Branch
 
736
 
 
737
        branch.lock_read()
 
738
        try:
 
739
            revision_a = revision.ensure_null(branch.last_revision())
 
740
            if revision_a == revision.NULL_REVISION:
 
741
                raise errors.NoCommits(branch)
 
742
            other_branch = Branch.open(other_location)
 
743
            other_branch.lock_read()
 
744
            try:
 
745
                revision_b = revision.ensure_null(other_branch.last_revision())
 
746
                if revision_b == revision.NULL_REVISION:
 
747
                    raise errors.NoCommits(other_branch)
 
748
                graph = branch.repository.get_graph(other_branch.repository)
 
749
                rev_id = graph.find_unique_lca(revision_a, revision_b)
 
750
            finally:
 
751
                other_branch.unlock()
 
752
            if rev_id == revision.NULL_REVISION:
 
753
                raise errors.NoCommonAncestor(revision_a, revision_b)
 
754
            return rev_id
 
755
        finally:
 
756
            branch.unlock()
 
757
 
 
758
 
 
759
SPEC_TYPES.append(RevisionSpec_ancestor)
 
760
 
 
761
 
 
762
class RevisionSpec_branch(RevisionSpec):
 
763
    """Selects the last revision of a specified branch."""
 
764
 
 
765
    help_txt = """Selects the last revision of a specified branch.
 
766
 
 
767
    Supply the path to a branch to select its last revision.
 
768
 
 
769
    Examples::
 
770
 
 
771
      branch:/path/to/branch
 
772
    """
 
773
    prefix = 'branch:'
 
774
 
 
775
    def _match_on(self, branch, revs):
 
776
        from bzrlib.branch import Branch
 
777
        other_branch = Branch.open(self.spec)
 
778
        revision_b = other_branch.last_revision()
 
779
        if revision_b in (None, revision.NULL_REVISION):
 
780
            raise errors.NoCommits(other_branch)
 
781
        # pull in the remote revisions so we can diff
 
782
        branch.fetch(other_branch, revision_b)
 
783
        try:
 
784
            revno = branch.revision_id_to_revno(revision_b)
 
785
        except errors.NoSuchRevision:
 
786
            revno = None
 
787
        return RevisionInfo(branch, revno, revision_b)
 
788
 
 
789
    def _as_revision_id(self, context_branch):
 
790
        from bzrlib.branch import Branch
 
791
        other_branch = Branch.open(self.spec)
 
792
        last_revision = other_branch.last_revision()
 
793
        last_revision = revision.ensure_null(last_revision)
 
794
        context_branch.fetch(other_branch, last_revision)
 
795
        if last_revision == revision.NULL_REVISION:
 
796
            raise errors.NoCommits(other_branch)
 
797
        return last_revision
 
798
 
 
799
    def _as_tree(self, context_branch):
 
800
        from bzrlib.branch import Branch
 
801
        other_branch = Branch.open(self.spec)
 
802
        last_revision = other_branch.last_revision()
 
803
        last_revision = revision.ensure_null(last_revision)
 
804
        if last_revision == revision.NULL_REVISION:
 
805
            raise errors.NoCommits(other_branch)
 
806
        return other_branch.repository.revision_tree(last_revision)
 
807
 
 
808
SPEC_TYPES.append(RevisionSpec_branch)
 
809
 
 
810
 
 
811
class RevisionSpec_submit(RevisionSpec_ancestor):
 
812
    """Selects a common ancestor with a submit branch."""
 
813
 
 
814
    help_txt = """Selects a common ancestor with the submit branch.
 
815
 
 
816
    Diffing against this shows all the changes that were made in this branch,
 
817
    and is a good predictor of what merge will do.  The submit branch is
 
818
    used by the bundle and merge directive commands.  If no submit branch
 
819
    is specified, the parent branch is used instead.
 
820
 
 
821
    The common ancestor is the last revision that existed in both
 
822
    branches. Usually this is the branch point, but it could also be
 
823
    a revision that was merged.
 
824
 
 
825
    Examples::
 
826
 
 
827
      $ bzr diff -r submit:
 
828
    """
 
829
 
 
830
    prefix = 'submit:'
 
831
 
 
832
    def _get_submit_location(self, branch):
 
833
        submit_location = branch.get_submit_branch()
 
834
        location_type = 'submit branch'
 
835
        if submit_location is None:
 
836
            submit_location = branch.get_parent()
 
837
            location_type = 'parent branch'
 
838
        if submit_location is None:
 
839
            raise errors.NoSubmitBranch(branch)
 
840
        trace.note('Using %s %s', location_type, submit_location)
 
841
        return submit_location
 
842
 
 
843
    def _match_on(self, branch, revs):
 
844
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
 
845
        return self._find_revision_info(branch,
 
846
            self._get_submit_location(branch))
 
847
 
 
848
    def _as_revision_id(self, context_branch):
 
849
        return self._find_revision_id(context_branch,
 
850
            self._get_submit_location(context_branch))
 
851
 
 
852
 
 
853
SPEC_TYPES.append(RevisionSpec_submit)