1
# Copyright (C) 2005 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
34
class RevisionInfo(object):
35
"""The results of applying a revision specification to a branch."""
37
help_txt = """The results of applying a revision specification to a branch.
39
An instance has two useful attributes: revno, and rev_id.
41
They can also be accessed as spec[0] and spec[1] respectively,
42
so that you can write code like:
43
revno, rev_id = RevisionSpec(branch, spec)
44
although this is probably going to be deprecated later.
46
This class exists mostly to be the return value of a RevisionSpec,
47
so that you can access the member you're interested in (number or id)
48
or treat the result as a tuple.
51
def __init__(self, branch, revno, rev_id=_marker):
55
# allow caller to be lazy
56
if self.revno is None:
59
self.rev_id = branch.get_rev_id(self.revno)
63
def __nonzero__(self):
64
# first the easy ones...
65
if self.rev_id is None:
67
if self.revno is not None:
69
# TODO: otherwise, it should depend on how I was built -
70
# if it's in_history(branch), then check revision_history(),
71
# if it's in_store(branch), do the check below
72
return self.branch.repository.has_revision(self.rev_id)
77
def __getitem__(self, index):
78
if index == 0: return self.revno
79
if index == 1: return self.rev_id
80
raise IndexError(index)
83
return self.branch.repository.get_revision(self.rev_id)
85
def __eq__(self, other):
86
if type(other) not in (tuple, list, type(self)):
88
if type(other) is type(self) and self.branch is not other.branch:
90
return tuple(self) == tuple(other)
93
return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
94
self.revno, self.rev_id, self.branch)
97
# classes in this list should have a "prefix" attribute, against which
98
# string specs are matched
103
class RevisionSpec(object):
104
"""A parsed revision specification."""
106
help_txt = """A parsed revision specification.
108
A revision specification can be an integer, in which case it is
109
assumed to be a revno (though this will translate negative values
110
into positive ones); or it can be a string, in which case it is
111
parsed for something like 'date:' or 'revid:' etc.
113
Revision specs are an UI element, and they have been moved out
114
of the branch class to leave "back-end" classes unaware of such
115
details. Code that gets a revno or rev_id from other code should
116
not be using revision specs - revnos and revision ids are the
117
accepted ways to refer to revisions internally.
119
(Equivalent to the old Branch method get_revision_info())
124
def __new__(cls, spec, _internal=False):
126
return object.__new__(cls, spec, _internal=_internal)
128
symbol_versioning.warn('Creating a RevisionSpec directly has'
129
' been deprecated in version 0.11. Use'
130
' RevisionSpec.from_string()'
132
DeprecationWarning, stacklevel=2)
133
return RevisionSpec.from_string(spec)
136
def from_string(spec):
137
"""Parse a revision spec string into a RevisionSpec object.
139
:param spec: A string specified by the user
140
:return: A RevisionSpec object that understands how to parse the
143
if not isinstance(spec, (type(None), basestring)):
144
raise TypeError('error')
147
return RevisionSpec(None, _internal=True)
149
assert isinstance(spec, basestring), \
150
"You should only supply strings not %s" % (type(spec),)
152
for spectype in SPEC_TYPES:
153
if spec.startswith(spectype.prefix):
154
trace.mutter('Returning RevisionSpec %s for %s',
155
spectype.__name__, spec)
156
return spectype(spec, _internal=True)
158
# RevisionSpec_revno is special cased, because it is the only
159
# one that directly handles plain integers
160
# TODO: This should not be special cased rather it should be
161
# a method invocation on spectype.canparse()
163
if _revno_regex is None:
164
_revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
165
if _revno_regex.match(spec) is not None:
166
return RevisionSpec_revno(spec, _internal=True)
168
raise errors.NoSuchRevisionSpec(spec)
170
def __init__(self, spec, _internal=False):
171
"""Create a RevisionSpec referring to the Null revision.
173
:param spec: The original spec supplied by the user
174
:param _internal: Used to ensure that RevisionSpec is not being
175
called directly. Only from RevisionSpec.from_string()
178
# XXX: Update this after 0.10 is released
179
symbol_versioning.warn('Creating a RevisionSpec directly has'
180
' been deprecated in version 0.11. Use'
181
' RevisionSpec.from_string()'
183
DeprecationWarning, stacklevel=2)
184
self.user_spec = spec
185
if self.prefix and spec.startswith(self.prefix):
186
spec = spec[len(self.prefix):]
189
def _match_on(self, branch, revs):
190
trace.mutter('Returning RevisionSpec._match_on: None')
191
return RevisionInfo(branch, 0, None)
193
def _match_on_and_check(self, branch, revs):
194
info = self._match_on(branch, revs)
197
elif info == (0, None):
198
# special case - the empty tree
201
raise errors.InvalidRevisionSpec(self.user_spec, branch)
203
raise errors.InvalidRevisionSpec(self.spec, branch)
205
def in_history(self, branch):
207
revs = branch.revision_history()
209
# this should never trigger.
210
# TODO: make it a deprecated code path. RBC 20060928
212
return self._match_on_and_check(branch, revs)
214
# FIXME: in_history is somewhat broken,
215
# it will return non-history revisions in many
216
# circumstances. The expected facility is that
217
# in_history only returns revision-history revs,
218
# in_store returns any rev. RBC 20051010
219
# aliases for now, when we fix the core logic, then they
220
# will do what you expect.
221
in_store = in_history
225
# this is mostly for helping with testing
226
return '<%s %s>' % (self.__class__.__name__,
229
def needs_branch(self):
230
"""Whether this revision spec needs a branch.
232
Set this to False the branch argument of _match_on is not used.
236
def get_branch(self):
237
"""When the revision specifier contains a branch location, return it.
239
Otherwise, return None.
246
class RevisionSpec_revno(RevisionSpec):
247
"""Selects a revision using a number."""
249
help_txt = """Selects a revision using a number.
251
Use an integer to specify a revision in the history of the branch.
252
Optionally a branch can be specified. The 'revno:' prefix is optional.
253
A negative number will count from the end of the branch (-1 is the
254
last revision, -2 the previous one). If the negative number is larger
255
than the branch's history, the first revision is returned.
257
revno:1 -> return the first revision
258
revno:3:/path/to/branch -> return the 3rd revision of
259
the branch '/path/to/branch'
260
revno:-1 -> The last revision in a branch.
261
-2:http://other/branch -> The second to last revision in the
263
-1000000 -> Most likely the first revision, unless
264
your history is very long.
268
def _match_on(self, branch, revs):
269
"""Lookup a revision by revision number"""
270
loc = self.spec.find(':')
272
revno_spec = self.spec
275
revno_spec = self.spec[:loc]
276
branch_spec = self.spec[loc+1:]
280
raise errors.InvalidRevisionSpec(self.user_spec,
281
branch, 'cannot have an empty revno and no branch')
285
revno = int(revno_spec)
288
# dotted decimal. This arguably should not be here
289
# but the from_string method is a little primitive
290
# right now - RBC 20060928
292
match_revno = tuple((int(number) for number in revno_spec.split('.')))
293
except ValueError, e:
294
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
299
# the user has override the branch to look in.
300
# we need to refresh the revision_history map and
302
from bzrlib.branch import Branch
303
branch = Branch.open(branch_spec)
304
# Need to use a new revision history
305
# because we are using a specific branch
306
revs = branch.revision_history()
311
last_rev = branch.last_revision()
312
merge_sorted_revisions = tsort.merge_sort(
313
branch.repository.get_revision_graph(last_rev),
317
return item[3] == match_revno
318
revisions = filter(match, merge_sorted_revisions)
321
if len(revisions) != 1:
322
return RevisionInfo(branch, None, None)
324
# there is no traditional 'revno' for dotted-decimal revnos.
325
# so for API compatability we return None.
326
return RevisionInfo(branch, None, revisions[0][1])
329
# if get_rev_id supported negative revnos, there would not be a
330
# need for this special case.
331
if (-revno) >= len(revs):
334
revno = len(revs) + revno + 1
336
revision_id = branch.get_rev_id(revno, revs)
337
except errors.NoSuchRevision:
338
raise errors.InvalidRevisionSpec(self.user_spec, branch)
339
return RevisionInfo(branch, revno, revision_id)
341
def needs_branch(self):
342
return self.spec.find(':') == -1
344
def get_branch(self):
345
if self.spec.find(':') == -1:
348
return self.spec[self.spec.find(':')+1:]
351
RevisionSpec_int = RevisionSpec_revno
353
SPEC_TYPES.append(RevisionSpec_revno)
356
class RevisionSpec_revid(RevisionSpec):
357
"""Selects a revision using the revision id."""
359
help_txt = """Selects a revision using the revision id.
361
Supply a specific revision id, that can be used to specify any
362
revision id in the ancestry of the branch.
363
Including merges, and pending merges.
365
revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
369
def _match_on(self, branch, revs):
371
revno = revs.index(self.spec) + 1
374
return RevisionInfo(branch, revno, self.spec)
376
SPEC_TYPES.append(RevisionSpec_revid)
379
class RevisionSpec_last(RevisionSpec):
380
"""Selects the nth revision from the end."""
382
help_txt = """Selects the nth revision from the end.
384
Supply a positive number to get the nth revision from the end.
385
This is the same as supplying negative numbers to the 'revno:' spec.
387
last:1 -> return the last revision
388
last:3 -> return the revision 2 before the end.
393
def _match_on(self, branch, revs):
396
raise errors.NoCommits(branch)
397
return RevisionInfo(branch, len(revs), revs[-1])
400
offset = int(self.spec)
401
except ValueError, e:
402
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
405
raise errors.InvalidRevisionSpec(self.user_spec, branch,
406
'you must supply a positive value')
407
revno = len(revs) - offset + 1
409
revision_id = branch.get_rev_id(revno, revs)
410
except errors.NoSuchRevision:
411
raise errors.InvalidRevisionSpec(self.user_spec, branch)
412
return RevisionInfo(branch, revno, revision_id)
414
SPEC_TYPES.append(RevisionSpec_last)
417
class RevisionSpec_before(RevisionSpec):
418
"""Selects the parent of the revision specified."""
420
help_txt = """Selects the parent of the revision specified.
422
Supply any revision spec to return the parent of that revision.
423
It is an error to request the parent of the null revision (before:0).
424
This is mostly useful when inspecting revisions that are not in the
425
revision history of a branch.
428
before:1913 -> Return the parent of revno 1913 (revno 1912)
429
before:revid:aaaa@bbbb-1234567890 -> return the parent of revision
431
bzr diff -r before:revid:aaaa..revid:aaaa
432
-> Find the changes between revision 'aaaa' and its parent.
433
(what changes did 'aaaa' introduce)
438
def _match_on(self, branch, revs):
439
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
441
raise errors.InvalidRevisionSpec(self.user_spec, branch,
442
'cannot go before the null: revision')
444
# We need to use the repository history here
445
rev = branch.repository.get_revision(r.rev_id)
446
if not rev.parent_ids:
450
revision_id = rev.parent_ids[0]
452
revno = revs.index(revision_id) + 1
458
revision_id = branch.get_rev_id(revno, revs)
459
except errors.NoSuchRevision:
460
raise errors.InvalidRevisionSpec(self.user_spec,
462
return RevisionInfo(branch, revno, revision_id)
464
SPEC_TYPES.append(RevisionSpec_before)
467
class RevisionSpec_tag(RevisionSpec):
468
"""To be implemented."""
470
help_txt = """To be implemented."""
474
def _match_on(self, branch, revs):
475
raise errors.InvalidRevisionSpec(self.user_spec, branch,
476
'tag: namespace registered,'
477
' but not implemented')
479
SPEC_TYPES.append(RevisionSpec_tag)
482
class _RevListToTimestamps(object):
483
"""This takes a list of revisions, and allows you to bisect by date"""
485
__slots__ = ['revs', 'branch']
487
def __init__(self, revs, branch):
491
def __getitem__(self, index):
492
"""Get the date of the index'd item"""
493
r = self.branch.repository.get_revision(self.revs[index])
494
# TODO: Handle timezone.
495
return datetime.datetime.fromtimestamp(r.timestamp)
498
return len(self.revs)
501
class RevisionSpec_date(RevisionSpec):
502
"""Selects a revision on the basis of a datestamp."""
504
help_txt = """Selects a revision on the basis of a datestamp.
506
Supply a datestamp to select the first revision that matches the date.
507
Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
508
Matches the first entry after a given date (either at midnight or
509
at a specified time).
511
One way to display all the changes since yesterday would be:
512
bzr log -r date:yesterday..-1
515
date:yesterday -> select the first revision since yesterday
516
date:2006-08-14,17:10:14 -> select the first revision after
517
August 14th, 2006 at 5:10pm.
520
_date_re = re.compile(
521
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
523
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
526
def _match_on(self, branch, revs):
527
"""Spec for date revisions:
529
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
530
matches the first entry after a given date (either at midnight or
531
at a specified time).
533
# XXX: This doesn't actually work
534
# So the proper way of saying 'give me all entries for today' is:
535
# -r date:yesterday..date:today
536
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
537
if self.spec.lower() == 'yesterday':
538
dt = today - datetime.timedelta(days=1)
539
elif self.spec.lower() == 'today':
541
elif self.spec.lower() == 'tomorrow':
542
dt = today + datetime.timedelta(days=1)
544
m = self._date_re.match(self.spec)
545
if not m or (not m.group('date') and not m.group('time')):
546
raise errors.InvalidRevisionSpec(self.user_spec,
547
branch, 'invalid date')
551
year = int(m.group('year'))
552
month = int(m.group('month'))
553
day = int(m.group('day'))
560
hour = int(m.group('hour'))
561
minute = int(m.group('minute'))
562
if m.group('second'):
563
second = int(m.group('second'))
567
hour, minute, second = 0,0,0
569
raise errors.InvalidRevisionSpec(self.user_spec,
570
branch, 'invalid date')
572
dt = datetime.datetime(year=year, month=month, day=day,
573
hour=hour, minute=minute, second=second)
576
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
580
return RevisionInfo(branch, None)
582
return RevisionInfo(branch, rev + 1)
584
SPEC_TYPES.append(RevisionSpec_date)
587
class RevisionSpec_ancestor(RevisionSpec):
588
"""Selects a common ancestor with a second branch."""
590
help_txt = """Selects a common ancestor with a second branch.
592
Supply the path to a branch to select the common ancestor.
594
The common ancestor is the last revision that existed in both
595
branches. Usually this is the branch point, but it could also be
596
a revision that was merged.
598
This is frequently used with 'diff' to return all of the changes
599
that your branch introduces, while excluding the changes that you
600
have not merged from the remote branch.
603
ancestor:/path/to/branch
604
$ bzr diff -r ancestor:../../mainline/branch
608
def _match_on(self, branch, revs):
609
from bzrlib.branch import Branch
611
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
612
other_branch = Branch.open(self.spec)
613
revision_a = branch.last_revision()
614
revision_b = other_branch.last_revision()
615
for r, b in ((revision_a, branch), (revision_b, other_branch)):
616
if r in (None, revision.NULL_REVISION):
617
raise errors.NoCommits(b)
618
revision_source = revision.MultipleRevisionSources(
619
branch.repository, other_branch.repository)
620
rev_id = revision.common_ancestor(revision_a, revision_b,
623
revno = branch.revision_id_to_revno(rev_id)
624
except errors.NoSuchRevision:
626
return RevisionInfo(branch, revno, rev_id)
628
SPEC_TYPES.append(RevisionSpec_ancestor)
631
class RevisionSpec_branch(RevisionSpec):
632
"""Selects the last revision of a specified branch."""
634
help_txt = """Selects the last revision of a specified branch.
636
Supply the path to a branch to select its last revision.
639
branch:/path/to/branch
643
def _match_on(self, branch, revs):
644
from bzrlib.branch import Branch
645
other_branch = Branch.open(self.spec)
646
revision_b = other_branch.last_revision()
647
if revision_b in (None, revision.NULL_REVISION):
648
raise errors.NoCommits(other_branch)
649
# pull in the remote revisions so we can diff
650
branch.fetch(other_branch, revision_b)
652
revno = branch.revision_id_to_revno(revision_b)
653
except errors.NoSuchRevision:
655
return RevisionInfo(branch, revno, revision_b)
657
SPEC_TYPES.append(RevisionSpec_branch)