1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
38
class RevisionInfo(object):
39
"""The results of applying a revision specification to a branch."""
41
help_txt = """The results of applying a revision specification to a branch.
43
An instance has two useful attributes: revno, and rev_id.
45
They can also be accessed as spec[0] and spec[1] respectively,
46
so that you can write code like:
47
revno, rev_id = RevisionSpec(branch, spec)
48
although this is probably going to be deprecated later.
50
This class exists mostly to be the return value of a RevisionSpec,
51
so that you can access the member you're interested in (number or id)
52
or treat the result as a tuple.
55
def __init__(self, branch, revno, rev_id=_marker):
59
# allow caller to be lazy
60
if self.revno is None:
63
self.rev_id = branch.get_rev_id(self.revno)
67
def __nonzero__(self):
68
# first the easy ones...
69
if self.rev_id is None:
71
if self.revno is not None:
73
# TODO: otherwise, it should depend on how I was built -
74
# if it's in_history(branch), then check revision_history(),
75
# if it's in_store(branch), do the check below
76
return self.branch.repository.has_revision(self.rev_id)
81
def __getitem__(self, index):
82
if index == 0: return self.revno
83
if index == 1: return self.rev_id
84
raise IndexError(index)
87
return self.branch.repository.get_revision(self.rev_id)
89
def __eq__(self, other):
90
if type(other) not in (tuple, list, type(self)):
92
if type(other) is type(self) and self.branch is not other.branch:
94
return tuple(self) == tuple(other)
97
return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
98
self.revno, self.rev_id, self.branch)
101
def from_revision_id(branch, revision_id, revs):
102
"""Construct a RevisionInfo given just the id.
104
Use this if you don't know or care what the revno is.
106
if revision_id == revision.NULL_REVISION:
107
return RevisionInfo(branch, 0, revision_id)
109
revno = revs.index(revision_id) + 1
112
return RevisionInfo(branch, revno, revision_id)
115
# classes in this list should have a "prefix" attribute, against which
116
# string specs are matched
121
class RevisionSpec(object):
122
"""A parsed revision specification."""
124
help_txt = """A parsed revision specification.
126
A revision specification can be an integer, in which case it is
127
assumed to be a revno (though this will translate negative values
128
into positive ones); or it can be a string, in which case it is
129
parsed for something like 'date:' or 'revid:' etc.
131
Revision specs are an UI element, and they have been moved out
132
of the branch class to leave "back-end" classes unaware of such
133
details. Code that gets a revno or rev_id from other code should
134
not be using revision specs - revnos and revision ids are the
135
accepted ways to refer to revisions internally.
137
(Equivalent to the old Branch method get_revision_info())
141
wants_revision_history = True
144
def from_string(spec):
145
"""Parse a revision spec string into a RevisionSpec object.
147
:param spec: A string specified by the user
148
:return: A RevisionSpec object that understands how to parse the
151
if not isinstance(spec, (type(None), basestring)):
152
raise TypeError('error')
155
return RevisionSpec(None, _internal=True)
156
for spectype in SPEC_TYPES:
157
if spec.startswith(spectype.prefix):
158
trace.mutter('Returning RevisionSpec %s for %s',
159
spectype.__name__, spec)
160
return spectype(spec, _internal=True)
162
# RevisionSpec_revno is special cased, because it is the only
163
# one that directly handles plain integers
164
# TODO: This should not be special cased rather it should be
165
# a method invocation on spectype.canparse()
167
if _revno_regex is None:
168
_revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
169
if _revno_regex.match(spec) is not None:
170
return RevisionSpec_revno(spec, _internal=True)
172
raise errors.NoSuchRevisionSpec(spec)
174
def __init__(self, spec, _internal=False):
175
"""Create a RevisionSpec referring to the Null revision.
177
:param spec: The original spec supplied by the user
178
:param _internal: Used to ensure that RevisionSpec is not being
179
called directly. Only from RevisionSpec.from_string()
182
# XXX: Update this after 0.10 is released
183
symbol_versioning.warn('Creating a RevisionSpec directly has'
184
' been deprecated in version 0.11. Use'
185
' RevisionSpec.from_string()'
187
DeprecationWarning, stacklevel=2)
188
self.user_spec = spec
189
if self.prefix and spec.startswith(self.prefix):
190
spec = spec[len(self.prefix):]
193
def _match_on(self, branch, revs):
194
trace.mutter('Returning RevisionSpec._match_on: None')
195
return RevisionInfo(branch, None, None)
197
def _match_on_and_check(self, branch, revs):
198
info = self._match_on(branch, revs)
201
elif info == (None, None):
202
# special case - nothing supplied
205
raise errors.InvalidRevisionSpec(self.user_spec, branch)
207
raise errors.InvalidRevisionSpec(self.spec, branch)
209
def in_history(self, branch):
211
if self.wants_revision_history:
212
revs = branch.revision_history()
216
# this should never trigger.
217
# TODO: make it a deprecated code path. RBC 20060928
219
return self._match_on_and_check(branch, revs)
221
# FIXME: in_history is somewhat broken,
222
# it will return non-history revisions in many
223
# circumstances. The expected facility is that
224
# in_history only returns revision-history revs,
225
# in_store returns any rev. RBC 20051010
226
# aliases for now, when we fix the core logic, then they
227
# will do what you expect.
228
in_store = in_history
231
def as_revision_id(self, context_branch):
232
"""Return just the revision_id for this revisions spec.
234
Some revision specs require a context_branch to be able to determine
235
their value. Not all specs will make use of it.
237
return self._as_revision_id(context_branch)
239
def _as_revision_id(self, context_branch):
240
"""Implementation of as_revision_id()
242
Classes should override this function to provide appropriate
243
functionality. The default is to just call '.in_history().rev_id'
245
return self.in_history(context_branch).rev_id
247
def as_tree(self, context_branch):
248
"""Return the tree object for this revisions spec.
250
Some revision specs require a context_branch to be able to determine
251
the revision id and access the repository. Not all specs will make
254
return self._as_tree(context_branch)
256
def _as_tree(self, context_branch):
257
"""Implementation of as_tree().
259
Classes should override this function to provide appropriate
260
functionality. The default is to just call '.as_revision_id()'
261
and get the revision tree from context_branch's repository.
263
revision_id = self.as_revision_id(context_branch)
264
return context_branch.repository.revision_tree(revision_id)
267
# this is mostly for helping with testing
268
return '<%s %s>' % (self.__class__.__name__,
271
def needs_branch(self):
272
"""Whether this revision spec needs a branch.
274
Set this to False the branch argument of _match_on is not used.
278
def get_branch(self):
279
"""When the revision specifier contains a branch location, return it.
281
Otherwise, return None.
288
class RevisionSpec_revno(RevisionSpec):
289
"""Selects a revision using a number."""
291
help_txt = """Selects a revision using a number.
293
Use an integer to specify a revision in the history of the branch.
294
Optionally a branch can be specified. The 'revno:' prefix is optional.
295
A negative number will count from the end of the branch (-1 is the
296
last revision, -2 the previous one). If the negative number is larger
297
than the branch's history, the first revision is returned.
300
revno:1 -> return the first revision of this branch
301
revno:3:/path/to/branch -> return the 3rd revision of
302
the branch '/path/to/branch'
303
revno:-1 -> The last revision in a branch.
304
-2:http://other/branch -> The second to last revision in the
306
-1000000 -> Most likely the first revision, unless
307
your history is very long.
310
wants_revision_history = False
312
def _match_on(self, branch, revs):
313
"""Lookup a revision by revision number"""
314
branch, revno, revision_id = self._lookup(branch, revs)
315
return RevisionInfo(branch, revno, revision_id)
317
def _lookup(self, branch, revs_or_none):
318
loc = self.spec.find(':')
320
revno_spec = self.spec
323
revno_spec = self.spec[:loc]
324
branch_spec = self.spec[loc+1:]
328
raise errors.InvalidRevisionSpec(self.user_spec,
329
branch, 'cannot have an empty revno and no branch')
333
revno = int(revno_spec)
336
# dotted decimal. This arguably should not be here
337
# but the from_string method is a little primitive
338
# right now - RBC 20060928
340
match_revno = tuple((int(number) for number in revno_spec.split('.')))
341
except ValueError, e:
342
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
347
# the user has override the branch to look in.
348
# we need to refresh the revision_history map and
350
from bzrlib.branch import Branch
351
branch = Branch.open(branch_spec)
356
revision_id = branch.dotted_revno_to_revision_id(match_revno,
358
except errors.NoSuchRevision:
359
raise errors.InvalidRevisionSpec(self.user_spec, branch)
361
# there is no traditional 'revno' for dotted-decimal revnos.
362
# so for API compatability we return None.
363
return branch, None, revision_id
365
last_revno, last_revision_id = branch.last_revision_info()
367
# if get_rev_id supported negative revnos, there would not be a
368
# need for this special case.
369
if (-revno) >= last_revno:
372
revno = last_revno + revno + 1
374
revision_id = branch.get_rev_id(revno, revs_or_none)
375
except errors.NoSuchRevision:
376
raise errors.InvalidRevisionSpec(self.user_spec, branch)
377
return branch, revno, revision_id
379
def _as_revision_id(self, context_branch):
380
# We would have the revno here, but we don't really care
381
branch, revno, revision_id = self._lookup(context_branch, None)
384
def needs_branch(self):
385
return self.spec.find(':') == -1
387
def get_branch(self):
388
if self.spec.find(':') == -1:
391
return self.spec[self.spec.find(':')+1:]
394
RevisionSpec_int = RevisionSpec_revno
396
SPEC_TYPES.append(RevisionSpec_revno)
399
class RevisionSpec_revid(RevisionSpec):
400
"""Selects a revision using the revision id."""
402
help_txt = """Selects a revision using the revision id.
404
Supply a specific revision id, that can be used to specify any
405
revision id in the ancestry of the branch.
406
Including merges, and pending merges.
409
revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
414
def _match_on(self, branch, revs):
415
# self.spec comes straight from parsing the command line arguments,
416
# so we expect it to be a Unicode string. Switch it to the internal
418
revision_id = osutils.safe_revision_id(self.spec, warn=False)
419
return RevisionInfo.from_revision_id(branch, revision_id, revs)
421
def _as_revision_id(self, context_branch):
422
return osutils.safe_revision_id(self.spec, warn=False)
424
SPEC_TYPES.append(RevisionSpec_revid)
427
class RevisionSpec_last(RevisionSpec):
428
"""Selects the nth revision from the end."""
430
help_txt = """Selects the nth revision from the end.
432
Supply a positive number to get the nth revision from the end.
433
This is the same as supplying negative numbers to the 'revno:' spec.
436
last:1 -> return the last revision
437
last:3 -> return the revision 2 before the end.
442
def _match_on(self, branch, revs):
443
revno, revision_id = self._revno_and_revision_id(branch, revs)
444
return RevisionInfo(branch, revno, revision_id)
446
def _revno_and_revision_id(self, context_branch, revs_or_none):
447
last_revno, last_revision_id = context_branch.last_revision_info()
451
raise errors.NoCommits(context_branch)
452
return last_revno, last_revision_id
455
offset = int(self.spec)
456
except ValueError, e:
457
raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
460
raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
461
'you must supply a positive value')
463
revno = last_revno - offset + 1
465
revision_id = context_branch.get_rev_id(revno, revs_or_none)
466
except errors.NoSuchRevision:
467
raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
468
return revno, revision_id
470
def _as_revision_id(self, context_branch):
471
# We compute the revno as part of the process, but we don't really care
473
revno, revision_id = self._revno_and_revision_id(context_branch, None)
476
SPEC_TYPES.append(RevisionSpec_last)
479
class RevisionSpec_before(RevisionSpec):
480
"""Selects the parent of the revision specified."""
482
help_txt = """Selects the parent of the revision specified.
484
Supply any revision spec to return the parent of that revision. This is
485
mostly useful when inspecting revisions that are not in the revision history
488
It is an error to request the parent of the null revision (before:0).
492
before:1913 -> Return the parent of revno 1913 (revno 1912)
493
before:revid:aaaa@bbbb-1234567890 -> return the parent of revision
495
bzr diff -r before:1913..1913
496
-> Find the changes between revision 1913 and its parent (1912).
497
(What changes did revision 1913 introduce).
498
This is equivalent to: bzr diff -c 1913
503
def _match_on(self, branch, revs):
504
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
506
raise errors.InvalidRevisionSpec(self.user_spec, branch,
507
'cannot go before the null: revision')
509
# We need to use the repository history here
510
rev = branch.repository.get_revision(r.rev_id)
511
if not rev.parent_ids:
513
revision_id = revision.NULL_REVISION
515
revision_id = rev.parent_ids[0]
517
revno = revs.index(revision_id) + 1
523
revision_id = branch.get_rev_id(revno, revs)
524
except errors.NoSuchRevision:
525
raise errors.InvalidRevisionSpec(self.user_spec,
527
return RevisionInfo(branch, revno, revision_id)
529
def _as_revision_id(self, context_branch):
530
base_revspec = RevisionSpec.from_string(self.spec)
531
base_revision_id = base_revspec.as_revision_id(context_branch)
532
if base_revision_id == revision.NULL_REVISION:
533
raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
534
'cannot go before the null: revision')
535
context_repo = context_branch.repository
536
context_repo.lock_read()
538
parent_map = context_repo.get_parent_map([base_revision_id])
540
context_repo.unlock()
541
if base_revision_id not in parent_map:
542
# Ghost, or unknown revision id
543
raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
544
'cannot find the matching revision')
545
parents = parent_map[base_revision_id]
547
raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
548
'No parents for revision.')
551
SPEC_TYPES.append(RevisionSpec_before)
554
class RevisionSpec_tag(RevisionSpec):
555
"""Select a revision identified by tag name"""
557
help_txt = """Selects a revision identified by a tag name.
559
Tags are stored in the branch and created by the 'tag' command.
564
def _match_on(self, branch, revs):
565
# Can raise tags not supported, NoSuchTag, etc
566
return RevisionInfo.from_revision_id(branch,
567
branch.tags.lookup_tag(self.spec),
570
def _as_revision_id(self, context_branch):
571
return context_branch.tags.lookup_tag(self.spec)
573
SPEC_TYPES.append(RevisionSpec_tag)
576
class _RevListToTimestamps(object):
577
"""This takes a list of revisions, and allows you to bisect by date"""
579
__slots__ = ['revs', 'branch']
581
def __init__(self, revs, branch):
585
def __getitem__(self, index):
586
"""Get the date of the index'd item"""
587
r = self.branch.repository.get_revision(self.revs[index])
588
# TODO: Handle timezone.
589
return datetime.datetime.fromtimestamp(r.timestamp)
592
return len(self.revs)
595
class RevisionSpec_date(RevisionSpec):
596
"""Selects a revision on the basis of a datestamp."""
598
help_txt = """Selects a revision on the basis of a datestamp.
600
Supply a datestamp to select the first revision that matches the date.
601
Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
602
Matches the first entry after a given date (either at midnight or
603
at a specified time).
605
One way to display all the changes since yesterday would be::
607
bzr log -r date:yesterday..
611
date:yesterday -> select the first revision since yesterday
612
date:2006-08-14,17:10:14 -> select the first revision after
613
August 14th, 2006 at 5:10pm.
616
_date_re = re.compile(
617
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
619
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
622
def _match_on(self, branch, revs):
623
"""Spec for date revisions:
625
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
626
matches the first entry after a given date (either at midnight or
627
at a specified time).
629
# XXX: This doesn't actually work
630
# So the proper way of saying 'give me all entries for today' is:
631
# -r date:yesterday..date:today
632
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
633
if self.spec.lower() == 'yesterday':
634
dt = today - datetime.timedelta(days=1)
635
elif self.spec.lower() == 'today':
637
elif self.spec.lower() == 'tomorrow':
638
dt = today + datetime.timedelta(days=1)
640
m = self._date_re.match(self.spec)
641
if not m or (not m.group('date') and not m.group('time')):
642
raise errors.InvalidRevisionSpec(self.user_spec,
643
branch, 'invalid date')
647
year = int(m.group('year'))
648
month = int(m.group('month'))
649
day = int(m.group('day'))
656
hour = int(m.group('hour'))
657
minute = int(m.group('minute'))
658
if m.group('second'):
659
second = int(m.group('second'))
663
hour, minute, second = 0,0,0
665
raise errors.InvalidRevisionSpec(self.user_spec,
666
branch, 'invalid date')
668
dt = datetime.datetime(year=year, month=month, day=day,
669
hour=hour, minute=minute, second=second)
672
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
676
raise errors.InvalidRevisionSpec(self.user_spec, branch)
678
return RevisionInfo(branch, rev + 1)
680
SPEC_TYPES.append(RevisionSpec_date)
683
class RevisionSpec_ancestor(RevisionSpec):
684
"""Selects a common ancestor with a second branch."""
686
help_txt = """Selects a common ancestor with a second branch.
688
Supply the path to a branch to select the common ancestor.
690
The common ancestor is the last revision that existed in both
691
branches. Usually this is the branch point, but it could also be
692
a revision that was merged.
694
This is frequently used with 'diff' to return all of the changes
695
that your branch introduces, while excluding the changes that you
696
have not merged from the remote branch.
700
ancestor:/path/to/branch
701
$ bzr diff -r ancestor:../../mainline/branch
705
def _match_on(self, branch, revs):
706
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
707
return self._find_revision_info(branch, self.spec)
709
def _as_revision_id(self, context_branch):
710
return self._find_revision_id(context_branch, self.spec)
713
def _find_revision_info(branch, other_location):
714
revision_id = RevisionSpec_ancestor._find_revision_id(branch,
717
revno = branch.revision_id_to_revno(revision_id)
718
except errors.NoSuchRevision:
720
return RevisionInfo(branch, revno, revision_id)
723
def _find_revision_id(branch, other_location):
724
from bzrlib.branch import Branch
728
revision_a = revision.ensure_null(branch.last_revision())
729
if revision_a == revision.NULL_REVISION:
730
raise errors.NoCommits(branch)
731
other_branch = Branch.open(other_location)
732
other_branch.lock_read()
734
revision_b = revision.ensure_null(other_branch.last_revision())
735
if revision_b == revision.NULL_REVISION:
736
raise errors.NoCommits(other_branch)
737
graph = branch.repository.get_graph(other_branch.repository)
738
rev_id = graph.find_unique_lca(revision_a, revision_b)
740
other_branch.unlock()
741
if rev_id == revision.NULL_REVISION:
742
raise errors.NoCommonAncestor(revision_a, revision_b)
748
SPEC_TYPES.append(RevisionSpec_ancestor)
751
class RevisionSpec_branch(RevisionSpec):
752
"""Selects the last revision of a specified branch."""
754
help_txt = """Selects the last revision of a specified branch.
756
Supply the path to a branch to select its last revision.
760
branch:/path/to/branch
764
def _match_on(self, branch, revs):
765
from bzrlib.branch import Branch
766
other_branch = Branch.open(self.spec)
767
revision_b = other_branch.last_revision()
768
if revision_b in (None, revision.NULL_REVISION):
769
raise errors.NoCommits(other_branch)
770
# pull in the remote revisions so we can diff
771
branch.fetch(other_branch, revision_b)
773
revno = branch.revision_id_to_revno(revision_b)
774
except errors.NoSuchRevision:
776
return RevisionInfo(branch, revno, revision_b)
778
def _as_revision_id(self, context_branch):
779
from bzrlib.branch import Branch
780
other_branch = Branch.open(self.spec)
781
last_revision = other_branch.last_revision()
782
last_revision = revision.ensure_null(last_revision)
783
context_branch.fetch(other_branch, last_revision)
784
if last_revision == revision.NULL_REVISION:
785
raise errors.NoCommits(other_branch)
788
def _as_tree(self, context_branch):
789
from bzrlib.branch import Branch
790
other_branch = Branch.open(self.spec)
791
last_revision = other_branch.last_revision()
792
last_revision = revision.ensure_null(last_revision)
793
if last_revision == revision.NULL_REVISION:
794
raise errors.NoCommits(other_branch)
795
return other_branch.repository.revision_tree(last_revision)
797
SPEC_TYPES.append(RevisionSpec_branch)
800
class RevisionSpec_submit(RevisionSpec_ancestor):
801
"""Selects a common ancestor with a submit branch."""
803
help_txt = """Selects a common ancestor with the submit branch.
805
Diffing against this shows all the changes that were made in this branch,
806
and is a good predictor of what merge will do. The submit branch is
807
used by the bundle and merge directive commands. If no submit branch
808
is specified, the parent branch is used instead.
810
The common ancestor is the last revision that existed in both
811
branches. Usually this is the branch point, but it could also be
812
a revision that was merged.
816
$ bzr diff -r submit:
821
def _get_submit_location(self, branch):
822
submit_location = branch.get_submit_branch()
823
location_type = 'submit branch'
824
if submit_location is None:
825
submit_location = branch.get_parent()
826
location_type = 'parent branch'
827
if submit_location is None:
828
raise errors.NoSubmitBranch(branch)
829
trace.note('Using %s %s', location_type, submit_location)
830
return submit_location
832
def _match_on(self, branch, revs):
833
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
834
return self._find_revision_info(branch,
835
self._get_submit_location(branch))
837
def _as_revision_id(self, context_branch):
838
return self._find_revision_id(context_branch,
839
self._get_submit_location(context_branch))
842
SPEC_TYPES.append(RevisionSpec_submit)