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
20
from bzrlib.lazy_import import lazy_import
17
from __future__ import absolute_import
20
from .lazy_import import lazy_import
21
21
lazy_import(globals(), """
26
branch as _mod_branch,
31
from breezy.i18n import gettext
45
class InvalidRevisionSpec(errors.BzrError):
47
_fmt = ("Requested revision: '%(spec)s' does not exist in branch:"
48
" %(branch_url)s%(extra)s")
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))
54
self.extra = '\n' + str(extra)
39
59
class RevisionInfo(object):
53
73
or treat the result as a tuple.
56
def __init__(self, branch, revno, rev_id=_marker):
76
def __init__(self, branch, revno=None, rev_id=None):
57
77
self.branch = branch
78
self._has_revno = (revno is not None)
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:
64
self.rev_id = branch.get_rev_id(self.revno)
68
def __nonzero__(self):
69
# first the easy ones...
83
self.rev_id = branch.get_rev_id(self._revno)
87
if not self._has_revno and self.rev_id is not None:
89
self._revno = self.branch.revision_id_to_revno(self.rev_id)
90
except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
92
self._has_revno = True
70
96
if self.rev_id is None:
72
if self.revno is not None:
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)
103
__nonzero__ = __bool__
79
105
def __len__(self):
82
108
def __getitem__(self, index):
83
if index == 0: return self.revno
84
if index == 1: return self.rev_id
85
113
raise IndexError(index)
90
118
def __eq__(self, other):
91
119
if type(other) not in (tuple, list, type(self)):
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:
95
123
return tuple(self) == tuple(other)
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)
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.
105
133
Use this if you don't know or care what the revno is.
107
if revision_id == revision.NULL_REVISION:
108
return RevisionInfo(branch, 0, revision_id)
110
revno = revs.index(revision_id) + 1
113
return RevisionInfo(branch, revno, revision_id)
135
return RevisionInfo(branch, revno=None, rev_id=revision_id)
119
138
class RevisionSpec(object):
205
215
# special case - nothing supplied
207
217
elif self.prefix:
208
raise errors.InvalidRevisionSpec(self.user_spec, branch)
218
raise InvalidRevisionSpec(self.user_spec, branch)
210
raise errors.InvalidRevisionSpec(self.spec, branch)
220
raise InvalidRevisionSpec(self.spec, branch)
212
222
def in_history(self, branch):
214
if self.wants_revision_history:
215
revs = branch.revision_history()
219
# this should never trigger.
220
# TODO: make it a deprecated code path. RBC 20060928
222
return self._match_on_and_check(branch, revs)
223
return self._match_on_and_check(branch, revs=None)
224
225
# FIXME: in_history is somewhat broken,
225
226
# it will return non-history revisions in many
312
315
"""Run the lookup and see what we can get."""
314
317
# First, see if it's a revno
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:
320
320
return self._try_spectype(RevisionSpec_revno, branch)
321
321
except RevisionSpec_revno.dwim_catchable_exceptions:
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()
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)
338
def append_possible_revspec(cls, revspec):
339
"""Append a possible DWIM revspec.
341
:param revspec: Revision spec to try.
343
cls._possible_revspecs.append(registry._ObjectGetter(revspec))
346
def append_possible_lazy_revspec(cls, module_name, member_name):
347
"""Append a possible lazily loaded DWIM revspec.
349
:param module_name: Name of the module with the revspec
350
:param member_name: Name of the revspec within the module
352
cls._possible_revspecs.append(
353
registry._LazyObjectGetter(module_name, member_name))
337
356
class RevisionSpec_revno(RevisionSpec):
356
375
your history is very long.
358
377
prefix = 'revno:'
359
wants_revision_history = False
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)
366
def _lookup(self, branch, revs_or_none):
384
def _lookup(self, branch):
367
385
loc = self.spec.find(':')
369
387
revno_spec = self.spec
370
388
branch_spec = None
372
390
revno_spec = self.spec[:loc]
373
branch_spec = self.spec[loc+1:]
391
branch_spec = self.spec[loc + 1:]
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')
386
404
# but the from_string method is a little primitive
387
405
# right now - RBC 20060928
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)
396
# the user has override the branch to look in.
397
# we need to refresh the revision_history map and
399
from bzrlib.branch import Branch
400
branch = Branch.open(branch_spec)
415
# the user has overriden the branch to look in.
416
branch = _mod_branch.Branch.open(branch_spec)
405
420
revision_id = branch.dotted_revno_to_revision_id(match_revno,
407
except errors.NoSuchRevision:
408
raise errors.InvalidRevisionSpec(self.user_spec, branch)
422
except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
423
raise InvalidRevisionSpec(self.user_spec, branch)
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
414
429
last_revno, last_revision_id = branch.last_revision_info()
421
436
revno = last_revno + revno + 1
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
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
433
448
def needs_branch(self):
460
482
prefix = 'revid:'
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)
469
def _as_revision_id(self, context_branch):
470
return osutils.safe_revision_id(self.spec, warn=False)
488
if isinstance(self.spec, text_type):
489
return cache_utf8.encode(self.spec)
474
493
class RevisionSpec_last(RevisionSpec):
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)
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')
510
529
revno = last_revno - offset + 1
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
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
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
525
543
class RevisionSpec_before(RevisionSpec):
526
544
"""Selects the parent of the revision specified."""
549
567
def _match_on(self, branch, revs):
550
568
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
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:
559
575
revision_id = revision.NULL_REVISION
561
577
revision_id = rev.parent_ids[0]
563
revno = revs.index(revision_id) + 1
567
580
revno = r.revno - 1
569
582
revision_id = branch.get_rev_id(revno, revs)
570
except errors.NoSuchRevision:
571
raise errors.InvalidRevisionSpec(self.user_spec,
583
except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
584
raise InvalidRevisionSpec(self.user_spec, branch)
573
585
return RevisionInfo(branch, revno, revision_id)
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()
595
with context_repo.lock_read():
584
596
parent_map = context_repo.get_parent_map([base_revision_id])
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]
599
608
class RevisionSpec_tag(RevisionSpec):
600
609
"""Select a revision identified by tag name"""
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),
622
branch.tags.lookup_tag(self.spec))
616
624
def _as_revision_id(self, context_branch):
617
625
return context_branch.tags.lookup_tag(self.spec)
621
628
class _RevListToTimestamps(object):
622
629
"""This takes a list of revisions, and allows you to bisect by date"""
624
__slots__ = ['revs', 'branch']
631
__slots__ = ['branch']
626
def __init__(self, revs, branch):
633
def __init__(self, branch):
628
634
self.branch = branch
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)
636
642
def __len__(self):
637
return len(self.revs)
643
return self.branch.revno()
640
646
class RevisionSpec_date(RevisionSpec):
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')
713
718
dt = datetime.datetime(year=year, month=month, day=day,
714
hour=hour, minute=minute, second=second)
717
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
721
raise errors.InvalidRevisionSpec(self.user_spec, branch)
723
return RevisionInfo(branch, rev + 1)
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)
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,
761
revno = branch.revision_id_to_revno(revision_id)
762
except errors.NoSuchRevision:
764
return RevisionInfo(branch, revno, revision_id)
760
return RevisionInfo(branch, None, revision_id)
767
763
def _find_revision_id(branch, other_location):
768
from bzrlib.branch import Branch
764
from .branch import Branch
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()
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)
786
other_branch.unlock()
787
779
if rev_id == revision.NULL_REVISION:
788
780
raise errors.NoCommonAncestor(revision_a, revision_b)
796
784
class RevisionSpec_branch(RevisionSpec):
808
796
dwim_catchable_exceptions = (errors.NotBranchError,)
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)
819
revno = branch.revision_id_to_revno(revision_b)
820
except errors.NoSuchRevision:
822
return RevisionInfo(branch, revno, revision_b)
805
branch = other_branch
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)
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)
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,
875
871
return submit_location
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))
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))
883
class RevisionSpec_annotate(RevisionIDSpec):
887
help_txt = """Select the revision that last modified the specified line.
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.
895
def _raise_invalid(self, numstring, context_branch):
896
raise InvalidRevisionSpec(self.user_spec, context_branch,
897
'No such line: %s' % numstring)
899
def _as_revision_id(self, context_branch):
900
path, numstring = self.spec.rsplit(':', 1)
902
index = int(numstring) - 1
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)]
913
revision_id = revision_ids[index]
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)
923
class RevisionSpec_mainline(RevisionIDSpec):
925
help_txt = """Select mainline revision that merged the specified revision.
927
Select the revision that merged the specified revision into mainline.
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
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())
943
raise InvalidRevisionSpec(self.user_spec, context_branch)
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
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
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)
898
955
revspec_registry = registry.Registry()
899
958
def _register_revspec(revspec):
900
959
revspec_registry.register(revspec.prefix, revspec)
902
962
_register_revspec(RevisionSpec_revno)
903
963
_register_revspec(RevisionSpec_revid)
904
964
_register_revspec(RevisionSpec_last)