/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-07-18 23:14:00 UTC
  • mfrom: (7490.40.62 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200718231400-jaes9qltn8oi8xss
Merge lp:brz/3.1.

Show diffs side-by-side

added added

removed removed

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