/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 breezy/revisionspec.py

  • Committer: Jelmer Vernooij
  • Date: 2020-09-02 15:11:17 UTC
  • mto: (7490.40.109 work)
  • mto: This revision was merged to the branch mainline in revision 7526.
  • Revision ID: jelmer@jelmer.uk-20200902151117-jeu7tarbz3dkuju0
Move more transform code.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
 
18
 
import re
19
 
 
20
 
from bzrlib.lazy_import import lazy_import
 
17
from __future__ import absolute_import
 
18
 
 
19
 
 
20
from .lazy_import import lazy_import
21
21
lazy_import(globals(), """
22
22
import bisect
23
23
import datetime
 
24
 
 
25
from breezy import (
 
26
    branch as _mod_branch,
 
27
    cache_utf8,
 
28
    revision,
 
29
    workingtree,
 
30
    )
 
31
from breezy.i18n import gettext
24
32
""")
25
33
 
26
 
from bzrlib import (
 
34
from . import (
27
35
    errors,
28
 
    osutils,
 
36
    lazy_regex,
29
37
    registry,
30
 
    revision,
31
 
    symbol_versioning,
32
38
    trace,
33
39
    )
34
 
 
35
 
 
36
 
_marker = []
 
40
from .sixish import (
 
41
    text_type,
 
42
    )
 
43
 
 
44
 
 
45
class InvalidRevisionSpec(errors.BzrError):
 
46
 
 
47
    _fmt = ("Requested revision: '%(spec)s' does not exist in branch:"
 
48
            " %(branch_url)s%(extra)s")
 
49
 
 
50
    def __init__(self, spec, branch, extra=None):
 
51
        errors.BzrError.__init__(self, branch=branch, spec=spec)
 
52
        self.branch_url = getattr(branch, 'user_url', str(branch))
 
53
        if extra:
 
54
            self.extra = '\n' + str(extra)
 
55
        else:
 
56
            self.extra = ''
37
57
 
38
58
 
39
59
class RevisionInfo(object):
53
73
    or treat the result as a tuple.
54
74
    """
55
75
 
56
 
    def __init__(self, branch, revno, rev_id=_marker):
 
76
    def __init__(self, branch, revno=None, rev_id=None):
57
77
        self.branch = branch
58
 
        self.revno = revno
59
 
        if rev_id is _marker:
 
78
        self._has_revno = (revno is not None)
 
79
        self._revno = revno
 
80
        self.rev_id = rev_id
 
81
        if self.rev_id is None and self._revno is not None:
60
82
            # allow caller to be lazy
61
 
            if self.revno is None:
62
 
                self.rev_id = None
63
 
            else:
64
 
                self.rev_id = branch.get_rev_id(self.revno)
65
 
        else:
66
 
            self.rev_id = rev_id
67
 
 
68
 
    def __nonzero__(self):
69
 
        # first the easy ones...
 
83
            self.rev_id = branch.get_rev_id(self._revno)
 
84
 
 
85
    @property
 
86
    def revno(self):
 
87
        if not self._has_revno and self.rev_id is not None:
 
88
            try:
 
89
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
 
90
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
91
                self._revno = None
 
92
            self._has_revno = True
 
93
        return self._revno
 
94
 
 
95
    def __bool__(self):
70
96
        if self.rev_id is None:
71
97
            return False
72
 
        if self.revno is not None:
73
 
            return True
74
98
        # TODO: otherwise, it should depend on how I was built -
75
99
        # if it's in_history(branch), then check revision_history(),
76
100
        # if it's in_store(branch), do the check below
77
101
        return self.branch.repository.has_revision(self.rev_id)
78
102
 
 
103
    __nonzero__ = __bool__
 
104
 
79
105
    def __len__(self):
80
106
        return 2
81
107
 
82
108
    def __getitem__(self, index):
83
 
        if index == 0: return self.revno
84
 
        if index == 1: return self.rev_id
 
109
        if index == 0:
 
110
            return self.revno
 
111
        if index == 1:
 
112
            return self.rev_id
85
113
        raise IndexError(index)
86
114
 
87
115
    def get(self):
90
118
    def __eq__(self, other):
91
119
        if type(other) not in (tuple, list, type(self)):
92
120
            return False
93
 
        if type(other) is type(self) and self.branch is not other.branch:
 
121
        if isinstance(other, type(self)) and self.branch is not other.branch:
94
122
            return False
95
123
        return tuple(self) == tuple(other)
96
124
 
97
125
    def __repr__(self):
98
 
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
 
126
        return '<breezy.revisionspec.RevisionInfo object %s, %s for %r>' % (
99
127
            self.revno, self.rev_id, self.branch)
100
128
 
101
129
    @staticmethod
102
 
    def from_revision_id(branch, revision_id, revs):
 
130
    def from_revision_id(branch, revision_id):
103
131
        """Construct a RevisionInfo given just the id.
104
132
 
105
133
        Use this if you don't know or care what the revno is.
106
134
        """
107
 
        if revision_id == revision.NULL_REVISION:
108
 
            return RevisionInfo(branch, 0, revision_id)
109
 
        try:
110
 
            revno = revs.index(revision_id) + 1
111
 
        except ValueError:
112
 
            revno = None
113
 
        return RevisionInfo(branch, revno, revision_id)
114
 
 
115
 
 
116
 
_revno_regex = None
 
135
        return RevisionInfo(branch, revno=None, rev_id=revision_id)
117
136
 
118
137
 
119
138
class RevisionSpec(object):
136
155
    """
137
156
 
138
157
    prefix = None
139
 
    wants_revision_history = True
140
 
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
 
158
    dwim_catchable_exceptions = (InvalidRevisionSpec,)
141
159
    """Exceptions that RevisionSpec_dwim._match_on will catch.
142
160
 
143
161
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
154
172
        :return: A RevisionSpec object that understands how to parse the
155
173
            supplied notation.
156
174
        """
157
 
        if not isinstance(spec, (type(None), basestring)):
158
 
            raise TypeError('error')
159
 
 
160
175
        if spec is None:
161
176
            return RevisionSpec(None, _internal=True)
 
177
        if not isinstance(spec, (str, text_type)):
 
178
            raise TypeError("revision spec needs to be text")
162
179
        match = revspec_registry.get_prefix(spec)
163
180
        if match is not None:
164
181
            spectype, specsuffix = match
166
183
                         spectype.__name__, spec)
167
184
            return spectype(spec, _internal=True)
168
185
        else:
169
 
            for spectype in SPEC_TYPES:
170
 
                if spec.startswith(spectype.prefix):
171
 
                    trace.mutter('Returning RevisionSpec %s for %s',
172
 
                                 spectype.__name__, spec)
173
 
                    return spectype(spec, _internal=True)
174
186
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
175
187
            # wait for _match_on to be called.
176
188
            return RevisionSpec_dwim(spec, _internal=True)
183
195
            called directly. Only from RevisionSpec.from_string()
184
196
        """
185
197
        if not _internal:
186
 
            symbol_versioning.warn('Creating a RevisionSpec directly has'
187
 
                                   ' been deprecated in version 0.11. Use'
188
 
                                   ' RevisionSpec.from_string()'
189
 
                                   ' instead.',
190
 
                                   DeprecationWarning, stacklevel=2)
 
198
            raise AssertionError(
 
199
                'Creating a RevisionSpec directly is not supported. '
 
200
                'Use RevisionSpec.from_string() instead.')
191
201
        self.user_spec = spec
192
202
        if self.prefix and spec.startswith(self.prefix):
193
203
            spec = spec[len(self.prefix):]
205
215
            # special case - nothing supplied
206
216
            return info
207
217
        elif self.prefix:
208
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
218
            raise InvalidRevisionSpec(self.user_spec, branch)
209
219
        else:
210
 
            raise errors.InvalidRevisionSpec(self.spec, branch)
 
220
            raise InvalidRevisionSpec(self.spec, branch)
211
221
 
212
222
    def in_history(self, branch):
213
 
        if branch:
214
 
            if self.wants_revision_history:
215
 
                revs = branch.revision_history()
216
 
            else:
217
 
                revs = None
218
 
        else:
219
 
            # this should never trigger.
220
 
            # TODO: make it a deprecated code path. RBC 20060928
221
 
            revs = None
222
 
        return self._match_on_and_check(branch, revs)
 
223
        return self._match_on_and_check(branch, revs=None)
223
224
 
224
225
        # FIXME: in_history is somewhat broken,
225
226
        # it will return non-history revisions in many
269
270
    def __repr__(self):
270
271
        # this is mostly for helping with testing
271
272
        return '<%s %s>' % (self.__class__.__name__,
272
 
                              self.user_spec)
 
273
                            self.user_spec)
273
274
 
274
275
    def needs_branch(self):
275
276
        """Whether this revision spec needs a branch.
298
299
    """
299
300
 
300
301
    help_txt = None
301
 
    # We don't need to build the revision history ourself, that's delegated to
302
 
    # each revspec we try.
303
 
    wants_revision_history = False
 
302
 
 
303
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
 
304
 
 
305
    # The revspecs to try
 
306
    _possible_revspecs = []
304
307
 
305
308
    def _try_spectype(self, rstype, branch):
306
309
        rs = rstype(self.spec, _internal=True)
312
315
        """Run the lookup and see what we can get."""
313
316
 
314
317
        # First, see if it's a revno
315
 
        global _revno_regex
316
 
        if _revno_regex is None:
317
 
            _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
318
 
        if _revno_regex.match(self.spec) is not None:
 
318
        if self._revno_regex.match(self.spec) is not None:
319
319
            try:
320
320
                return self._try_spectype(RevisionSpec_revno, branch)
321
321
            except RevisionSpec_revno.dwim_catchable_exceptions:
322
322
                pass
323
323
 
324
324
        # Next see what has been registered
325
 
        for rs_class in dwim_revspecs:
 
325
        for objgetter in self._possible_revspecs:
 
326
            rs_class = objgetter.get_obj()
326
327
            try:
327
328
                return self._try_spectype(rs_class, branch)
328
329
            except rs_class.dwim_catchable_exceptions:
331
332
        # Well, I dunno what it is. Note that we don't try to keep track of the
332
333
        # first of last exception raised during the DWIM tries as none seems
333
334
        # really relevant.
334
 
        raise errors.InvalidRevisionSpec(self.spec, branch)
 
335
        raise InvalidRevisionSpec(self.spec, branch)
 
336
 
 
337
    @classmethod
 
338
    def append_possible_revspec(cls, revspec):
 
339
        """Append a possible DWIM revspec.
 
340
 
 
341
        :param revspec: Revision spec to try.
 
342
        """
 
343
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
 
344
 
 
345
    @classmethod
 
346
    def append_possible_lazy_revspec(cls, module_name, member_name):
 
347
        """Append a possible lazily loaded DWIM revspec.
 
348
 
 
349
        :param module_name: Name of the module with the revspec
 
350
        :param member_name: Name of the revspec within the module
 
351
        """
 
352
        cls._possible_revspecs.append(
 
353
            registry._LazyObjectGetter(module_name, member_name))
335
354
 
336
355
 
337
356
class RevisionSpec_revno(RevisionSpec):
356
375
                                   your history is very long.
357
376
    """
358
377
    prefix = 'revno:'
359
 
    wants_revision_history = False
360
378
 
361
379
    def _match_on(self, branch, revs):
362
380
        """Lookup a revision by revision number"""
363
 
        branch, revno, revision_id = self._lookup(branch, revs)
 
381
        branch, revno, revision_id = self._lookup(branch)
364
382
        return RevisionInfo(branch, revno, revision_id)
365
383
 
366
 
    def _lookup(self, branch, revs_or_none):
 
384
    def _lookup(self, branch):
367
385
        loc = self.spec.find(':')
368
386
        if loc == -1:
369
387
            revno_spec = self.spec
370
388
            branch_spec = None
371
389
        else:
372
390
            revno_spec = self.spec[:loc]
373
 
            branch_spec = self.spec[loc+1:]
 
391
            branch_spec = self.spec[loc + 1:]
374
392
 
375
393
        if revno_spec == '':
376
394
            if not branch_spec:
377
 
                raise errors.InvalidRevisionSpec(self.user_spec,
378
 
                        branch, 'cannot have an empty revno and no branch')
 
395
                raise InvalidRevisionSpec(
 
396
                    self.user_spec, branch, 'cannot have an empty revno and no branch')
379
397
            revno = None
380
398
        else:
381
399
            try:
386
404
                # but the from_string method is a little primitive
387
405
                # right now - RBC 20060928
388
406
                try:
389
 
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
390
 
                except ValueError, e:
391
 
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
 
407
                    match_revno = tuple((int(number)
 
408
                                         for number in revno_spec.split('.')))
 
409
                except ValueError as e:
 
410
                    raise InvalidRevisionSpec(self.user_spec, branch, e)
392
411
 
393
412
                dotted = True
394
413
 
395
414
        if branch_spec:
396
 
            # the user has override the branch to look in.
397
 
            # we need to refresh the revision_history map and
398
 
            # the branch object.
399
 
            from bzrlib.branch import Branch
400
 
            branch = Branch.open(branch_spec)
401
 
            revs_or_none = None
 
415
            # the user has overriden the branch to look in.
 
416
            branch = _mod_branch.Branch.open(branch_spec)
402
417
 
403
418
        if dotted:
404
419
            try:
405
420
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
406
 
                    _cache_reverse=True)
407
 
            except errors.NoSuchRevision:
408
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
421
                                                                 _cache_reverse=True)
 
422
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
423
                raise InvalidRevisionSpec(self.user_spec, branch)
409
424
            else:
410
425
                # there is no traditional 'revno' for dotted-decimal revnos.
411
 
                # so for  API compatability we return None.
 
426
                # so for API compatibility we return None.
412
427
                return branch, None, revision_id
413
428
        else:
414
429
            last_revno, last_revision_id = branch.last_revision_info()
420
435
                else:
421
436
                    revno = last_revno + revno + 1
422
437
            try:
423
 
                revision_id = branch.get_rev_id(revno, revs_or_none)
424
 
            except errors.NoSuchRevision:
425
 
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
 
438
                revision_id = branch.get_rev_id(revno)
 
439
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
440
                raise InvalidRevisionSpec(self.user_spec, branch)
426
441
        return branch, revno, revision_id
427
442
 
428
443
    def _as_revision_id(self, context_branch):
429
444
        # We would have the revno here, but we don't really care
430
 
        branch, revno, revision_id = self._lookup(context_branch, None)
 
445
        branch, revno, revision_id = self._lookup(context_branch)
431
446
        return revision_id
432
447
 
433
448
    def needs_branch(self):
437
452
        if self.spec.find(':') == -1:
438
453
            return None
439
454
        else:
440
 
            return self.spec[self.spec.find(':')+1:]
 
455
            return self.spec[self.spec.find(':') + 1:]
 
456
 
441
457
 
442
458
# Old compatibility
443
459
RevisionSpec_int = RevisionSpec_revno
444
460
 
445
461
 
446
 
 
447
 
class RevisionSpec_revid(RevisionSpec):
 
462
class RevisionIDSpec(RevisionSpec):
 
463
 
 
464
    def _match_on(self, branch, revs):
 
465
        revision_id = self.as_revision_id(branch)
 
466
        return RevisionInfo.from_revision_id(branch, revision_id)
 
467
 
 
468
 
 
469
class RevisionSpec_revid(RevisionIDSpec):
448
470
    """Selects a revision using the revision id."""
449
471
 
450
472
    help_txt = """Selects a revision using the revision id.
459
481
 
460
482
    prefix = 'revid:'
461
483
 
462
 
    def _match_on(self, branch, revs):
 
484
    def _as_revision_id(self, context_branch):
463
485
        # self.spec comes straight from parsing the command line arguments,
464
486
        # so we expect it to be a Unicode string. Switch it to the internal
465
487
        # representation.
466
 
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
467
 
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
468
 
 
469
 
    def _as_revision_id(self, context_branch):
470
 
        return osutils.safe_revision_id(self.spec, warn=False)
471
 
 
 
488
        if isinstance(self.spec, text_type):
 
489
            return cache_utf8.encode(self.spec)
 
490
        return self.spec
472
491
 
473
492
 
474
493
class RevisionSpec_last(RevisionSpec):
487
506
    prefix = 'last:'
488
507
 
489
508
    def _match_on(self, branch, revs):
490
 
        revno, revision_id = self._revno_and_revision_id(branch, revs)
 
509
        revno, revision_id = self._revno_and_revision_id(branch)
491
510
        return RevisionInfo(branch, revno, revision_id)
492
511
 
493
 
    def _revno_and_revision_id(self, context_branch, revs_or_none):
 
512
    def _revno_and_revision_id(self, context_branch):
494
513
        last_revno, last_revision_id = context_branch.last_revision_info()
495
514
 
496
515
        if self.spec == '':
500
519
 
501
520
        try:
502
521
            offset = int(self.spec)
503
 
        except ValueError, e:
504
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
 
522
        except ValueError as e:
 
523
            raise InvalidRevisionSpec(self.user_spec, context_branch, e)
505
524
 
506
525
        if offset <= 0:
507
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
 
526
            raise InvalidRevisionSpec(self.user_spec, context_branch,
508
527
                                             'you must supply a positive value')
509
528
 
510
529
        revno = last_revno - offset + 1
511
530
        try:
512
 
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
513
 
        except errors.NoSuchRevision:
514
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
 
531
            revision_id = context_branch.get_rev_id(revno)
 
532
        except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
533
            raise InvalidRevisionSpec(self.user_spec, context_branch)
515
534
        return revno, revision_id
516
535
 
517
536
    def _as_revision_id(self, context_branch):
518
537
        # We compute the revno as part of the process, but we don't really care
519
538
        # about it.
520
 
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
 
539
        revno, revision_id = self._revno_and_revision_id(context_branch)
521
540
        return revision_id
522
541
 
523
542
 
524
 
 
525
543
class RevisionSpec_before(RevisionSpec):
526
544
    """Selects the parent of the revision specified."""
527
545
 
549
567
    def _match_on(self, branch, revs):
550
568
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
551
569
        if r.revno == 0:
552
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
553
 
                                         'cannot go before the null: revision')
 
570
            raise InvalidRevisionSpec(self.user_spec, branch, 'cannot go before the null: revision')
554
571
        if r.revno is None:
555
572
            # We need to use the repository history here
556
573
            rev = branch.repository.get_revision(r.rev_id)
557
574
            if not rev.parent_ids:
558
 
                revno = 0
559
575
                revision_id = revision.NULL_REVISION
560
576
            else:
561
577
                revision_id = rev.parent_ids[0]
562
 
                try:
563
 
                    revno = revs.index(revision_id) + 1
564
 
                except ValueError:
565
 
                    revno = None
 
578
            revno = None
566
579
        else:
567
580
            revno = r.revno - 1
568
581
            try:
569
582
                revision_id = branch.get_rev_id(revno, revs)
570
 
            except errors.NoSuchRevision:
571
 
                raise errors.InvalidRevisionSpec(self.user_spec,
572
 
                                                 branch)
 
583
            except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
 
584
                raise InvalidRevisionSpec(self.user_spec, branch)
573
585
        return RevisionInfo(branch, revno, revision_id)
574
586
 
575
587
    def _as_revision_id(self, context_branch):
576
 
        base_revspec = RevisionSpec.from_string(self.spec)
577
 
        base_revision_id = base_revspec.as_revision_id(context_branch)
 
588
        base_revision_id = RevisionSpec.from_string(
 
589
            self.spec)._as_revision_id(context_branch)
578
590
        if base_revision_id == revision.NULL_REVISION:
579
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
580
 
                                         'cannot go before the null: revision')
 
591
            raise InvalidRevisionSpec(
 
592
                self.user_spec, context_branch,
 
593
                'cannot go before the null: revision')
581
594
        context_repo = context_branch.repository
582
 
        context_repo.lock_read()
583
 
        try:
 
595
        with context_repo.lock_read():
584
596
            parent_map = context_repo.get_parent_map([base_revision_id])
585
 
        finally:
586
 
            context_repo.unlock()
587
597
        if base_revision_id not in parent_map:
588
598
            # Ghost, or unknown revision id
589
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
590
 
                'cannot find the matching revision')
 
599
            raise InvalidRevisionSpec(
 
600
                self.user_spec, context_branch, 'cannot find the matching revision')
591
601
        parents = parent_map[base_revision_id]
592
602
        if len(parents) < 1:
593
 
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
594
 
                'No parents for revision.')
 
603
            raise InvalidRevisionSpec(
 
604
                self.user_spec, context_branch, 'No parents for revision.')
595
605
        return parents[0]
596
606
 
597
607
 
598
 
 
599
608
class RevisionSpec_tag(RevisionSpec):
600
609
    """Select a revision identified by tag name"""
601
610
 
610
619
    def _match_on(self, branch, revs):
611
620
        # Can raise tags not supported, NoSuchTag, etc
612
621
        return RevisionInfo.from_revision_id(branch,
613
 
            branch.tags.lookup_tag(self.spec),
614
 
            revs)
 
622
                                             branch.tags.lookup_tag(self.spec))
615
623
 
616
624
    def _as_revision_id(self, context_branch):
617
625
        return context_branch.tags.lookup_tag(self.spec)
618
626
 
619
627
 
620
 
 
621
628
class _RevListToTimestamps(object):
622
629
    """This takes a list of revisions, and allows you to bisect by date"""
623
630
 
624
 
    __slots__ = ['revs', 'branch']
 
631
    __slots__ = ['branch']
625
632
 
626
 
    def __init__(self, revs, branch):
627
 
        self.revs = revs
 
633
    def __init__(self, branch):
628
634
        self.branch = branch
629
635
 
630
636
    def __getitem__(self, index):
631
637
        """Get the date of the index'd item"""
632
 
        r = self.branch.repository.get_revision(self.revs[index])
 
638
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
633
639
        # TODO: Handle timezone.
634
640
        return datetime.datetime.fromtimestamp(r.timestamp)
635
641
 
636
642
    def __len__(self):
637
 
        return len(self.revs)
 
643
        return self.branch.revno()
638
644
 
639
645
 
640
646
class RevisionSpec_date(RevisionSpec):
649
655
 
650
656
    One way to display all the changes since yesterday would be::
651
657
 
652
 
        bzr log -r date:yesterday..
 
658
        brz log -r date:yesterday..
653
659
 
654
660
    Examples::
655
661
 
658
664
                                   August 14th, 2006 at 5:10pm.
659
665
    """
660
666
    prefix = 'date:'
661
 
    _date_re = re.compile(
662
 
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
663
 
            r'(,|T)?\s*'
664
 
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
667
    _date_regex = lazy_regex.lazy_compile(
 
668
        r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
669
        r'(,|T)?\s*'
 
670
        r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
665
671
        )
666
672
 
667
673
    def _match_on(self, branch, revs):
674
680
        #  XXX: This doesn't actually work
675
681
        #  So the proper way of saying 'give me all entries for today' is:
676
682
        #      -r date:yesterday..date:today
677
 
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
 
683
        today = datetime.datetime.fromordinal(
 
684
            datetime.date.today().toordinal())
678
685
        if self.spec.lower() == 'yesterday':
679
686
            dt = today - datetime.timedelta(days=1)
680
687
        elif self.spec.lower() == 'today':
682
689
        elif self.spec.lower() == 'tomorrow':
683
690
            dt = today + datetime.timedelta(days=1)
684
691
        else:
685
 
            m = self._date_re.match(self.spec)
 
692
            m = self._date_regex.match(self.spec)
686
693
            if not m or (not m.group('date') and not m.group('time')):
687
 
                raise errors.InvalidRevisionSpec(self.user_spec,
688
 
                                                 branch, 'invalid date')
 
694
                raise InvalidRevisionSpec(self.user_spec, branch, 'invalid date')
689
695
 
690
696
            try:
691
697
                if m.group('date'):
705
711
                    else:
706
712
                        second = 0
707
713
                else:
708
 
                    hour, minute, second = 0,0,0
 
714
                    hour, minute, second = 0, 0, 0
709
715
            except ValueError:
710
 
                raise errors.InvalidRevisionSpec(self.user_spec,
711
 
                                                 branch, 'invalid date')
 
716
                raise InvalidRevisionSpec(self.user_spec, branch, 'invalid date')
712
717
 
713
718
            dt = datetime.datetime(year=year, month=month, day=day,
714
 
                    hour=hour, minute=minute, second=second)
715
 
        branch.lock_read()
716
 
        try:
717
 
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
718
 
        finally:
719
 
            branch.unlock()
720
 
        if rev == len(revs):
721
 
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
722
 
        else:
723
 
            return RevisionInfo(branch, rev + 1)
724
 
 
 
719
                                   hour=hour, minute=minute, second=second)
 
720
        with branch.lock_read():
 
721
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
 
722
        if rev == branch.revno():
 
723
            raise InvalidRevisionSpec(self.user_spec, branch)
 
724
        return RevisionInfo(branch, rev)
725
725
 
726
726
 
727
727
class RevisionSpec_ancestor(RevisionSpec):
757
757
    def _find_revision_info(branch, other_location):
758
758
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
759
759
                                                              other_location)
760
 
        try:
761
 
            revno = branch.revision_id_to_revno(revision_id)
762
 
        except errors.NoSuchRevision:
763
 
            revno = None
764
 
        return RevisionInfo(branch, revno, revision_id)
 
760
        return RevisionInfo(branch, None, revision_id)
765
761
 
766
762
    @staticmethod
767
763
    def _find_revision_id(branch, other_location):
768
 
        from bzrlib.branch import Branch
 
764
        from .branch import Branch
769
765
 
770
 
        branch.lock_read()
771
 
        try:
 
766
        with branch.lock_read():
772
767
            revision_a = revision.ensure_null(branch.last_revision())
773
768
            if revision_a == revision.NULL_REVISION:
774
769
                raise errors.NoCommits(branch)
775
770
            if other_location == '':
776
771
                other_location = branch.get_parent()
777
772
            other_branch = Branch.open(other_location)
778
 
            other_branch.lock_read()
779
 
            try:
 
773
            with other_branch.lock_read():
780
774
                revision_b = revision.ensure_null(other_branch.last_revision())
781
775
                if revision_b == revision.NULL_REVISION:
782
776
                    raise errors.NoCommits(other_branch)
783
777
                graph = branch.repository.get_graph(other_branch.repository)
784
778
                rev_id = graph.find_unique_lca(revision_a, revision_b)
785
 
            finally:
786
 
                other_branch.unlock()
787
779
            if rev_id == revision.NULL_REVISION:
788
780
                raise errors.NoCommonAncestor(revision_a, revision_b)
789
781
            return rev_id
790
 
        finally:
791
 
            branch.unlock()
792
 
 
793
 
 
794
782
 
795
783
 
796
784
class RevisionSpec_branch(RevisionSpec):
808
796
    dwim_catchable_exceptions = (errors.NotBranchError,)
809
797
 
810
798
    def _match_on(self, branch, revs):
811
 
        from bzrlib.branch import Branch
 
799
        from .branch import Branch
812
800
        other_branch = Branch.open(self.spec)
813
801
        revision_b = other_branch.last_revision()
814
802
        if revision_b in (None, revision.NULL_REVISION):
815
803
            raise errors.NoCommits(other_branch)
816
 
        # pull in the remote revisions so we can diff
817
 
        branch.fetch(other_branch, revision_b)
818
 
        try:
819
 
            revno = branch.revision_id_to_revno(revision_b)
820
 
        except errors.NoSuchRevision:
821
 
            revno = None
822
 
        return RevisionInfo(branch, revno, revision_b)
 
804
        if branch is None:
 
805
            branch = other_branch
 
806
        else:
 
807
            try:
 
808
                # pull in the remote revisions so we can diff
 
809
                branch.fetch(other_branch, revision_b)
 
810
            except errors.ReadOnlyError:
 
811
                branch = other_branch
 
812
        return RevisionInfo(branch, None, revision_b)
823
813
 
824
814
    def _as_revision_id(self, context_branch):
825
 
        from bzrlib.branch import Branch
 
815
        from .branch import Branch
826
816
        other_branch = Branch.open(self.spec)
827
817
        last_revision = other_branch.last_revision()
828
818
        last_revision = revision.ensure_null(last_revision)
832
822
        return last_revision
833
823
 
834
824
    def _as_tree(self, context_branch):
835
 
        from bzrlib.branch import Branch
 
825
        from .branch import Branch
836
826
        other_branch = Branch.open(self.spec)
837
827
        last_revision = other_branch.last_revision()
838
828
        last_revision = revision.ensure_null(last_revision)
840
830
            raise errors.NoCommits(other_branch)
841
831
        return other_branch.repository.revision_tree(last_revision)
842
832
 
 
833
    def needs_branch(self):
 
834
        return False
 
835
 
 
836
    def get_branch(self):
 
837
        return self.spec
843
838
 
844
839
 
845
840
class RevisionSpec_submit(RevisionSpec_ancestor):
871
866
            location_type = 'parent branch'
872
867
        if submit_location is None:
873
868
            raise errors.NoSubmitBranch(branch)
874
 
        trace.note('Using %s %s', location_type, submit_location)
 
869
        trace.note(gettext('Using {0} {1}').format(location_type,
 
870
                                                   submit_location))
875
871
        return submit_location
876
872
 
877
873
    def _match_on(self, branch, revs):
878
874
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
879
875
        return self._find_revision_info(branch,
880
 
            self._get_submit_location(branch))
 
876
                                        self._get_submit_location(branch))
881
877
 
882
878
    def _as_revision_id(self, context_branch):
883
879
        return self._find_revision_id(context_branch,
884
 
            self._get_submit_location(context_branch))
 
880
                                      self._get_submit_location(context_branch))
 
881
 
 
882
 
 
883
class RevisionSpec_annotate(RevisionIDSpec):
 
884
 
 
885
    prefix = 'annotate:'
 
886
 
 
887
    help_txt = """Select the revision that last modified the specified line.
 
888
 
 
889
    Select the revision that last modified the specified line.  Line is
 
890
    specified as path:number.  Path is a relative path to the file.  Numbers
 
891
    start at 1, and are relative to the current version, not the last-
 
892
    committed version of the file.
 
893
    """
 
894
 
 
895
    def _raise_invalid(self, numstring, context_branch):
 
896
        raise InvalidRevisionSpec(self.user_spec, context_branch,
 
897
                                  'No such line: %s' % numstring)
 
898
 
 
899
    def _as_revision_id(self, context_branch):
 
900
        path, numstring = self.spec.rsplit(':', 1)
 
901
        try:
 
902
            index = int(numstring) - 1
 
903
        except ValueError:
 
904
            self._raise_invalid(numstring, context_branch)
 
905
        tree, file_path = workingtree.WorkingTree.open_containing(path)
 
906
        with tree.lock_read():
 
907
            if not tree.has_filename(file_path):
 
908
                raise InvalidRevisionSpec(
 
909
                    self.user_spec, context_branch,
 
910
                    "File '%s' is not versioned." % file_path)
 
911
            revision_ids = [r for (r, l) in tree.annotate_iter(file_path)]
 
912
        try:
 
913
            revision_id = revision_ids[index]
 
914
        except IndexError:
 
915
            self._raise_invalid(numstring, context_branch)
 
916
        if revision_id == revision.CURRENT_REVISION:
 
917
            raise InvalidRevisionSpec(
 
918
                self.user_spec, context_branch,
 
919
                'Line %s has not been committed.' % numstring)
 
920
        return revision_id
 
921
 
 
922
 
 
923
class RevisionSpec_mainline(RevisionIDSpec):
 
924
 
 
925
    help_txt = """Select mainline revision that merged the specified revision.
 
926
 
 
927
    Select the revision that merged the specified revision into mainline.
 
928
    """
 
929
 
 
930
    prefix = 'mainline:'
 
931
 
 
932
    def _as_revision_id(self, context_branch):
 
933
        revspec = RevisionSpec.from_string(self.spec)
 
934
        if revspec.get_branch() is None:
 
935
            spec_branch = context_branch
 
936
        else:
 
937
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
 
938
        revision_id = revspec.as_revision_id(spec_branch)
 
939
        graph = context_branch.repository.get_graph()
 
940
        result = graph.find_lefthand_merger(revision_id,
 
941
                                            context_branch.last_revision())
 
942
        if result is None:
 
943
            raise InvalidRevisionSpec(self.user_spec, context_branch)
 
944
        return result
885
945
 
886
946
 
887
947
# The order in which we want to DWIM a revision spec without any prefix.
888
948
# revno is always tried first and isn't listed here, this is used by
889
949
# RevisionSpec_dwim._match_on
890
 
dwim_revspecs = [
891
 
    RevisionSpec_tag, # Let's try for a tag
892
 
    RevisionSpec_revid, # Maybe it's a revid?
893
 
    RevisionSpec_date, # Perhaps a date?
894
 
    RevisionSpec_branch, # OK, last try, maybe it's a branch
895
 
    ]
896
 
 
 
950
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
 
951
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
 
952
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
 
953
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
897
954
 
898
955
revspec_registry = registry.Registry()
 
956
 
 
957
 
899
958
def _register_revspec(revspec):
900
959
    revspec_registry.register(revspec.prefix, revspec)
901
960
 
 
961
 
902
962
_register_revspec(RevisionSpec_revno)
903
963
_register_revspec(RevisionSpec_revid)
904
964
_register_revspec(RevisionSpec_last)
908
968
_register_revspec(RevisionSpec_ancestor)
909
969
_register_revspec(RevisionSpec_branch)
910
970
_register_revspec(RevisionSpec_submit)
911
 
 
912
 
# classes in this list should have a "prefix" attribute, against which
913
 
# string specs are matched
914
 
SPEC_TYPES = symbol_versioning.deprecated_list(
915
 
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])
 
971
_register_revspec(RevisionSpec_annotate)
 
972
_register_revspec(RevisionSpec_mainline)