~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/revisionspec.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-06 22:37:30 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060606223730-a308c5429fc6c617
change branch.{get,set}_parent to store a relative path but return full urls

Show diffs side-by-side

added added

removed removed

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