/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2005-2010 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
16
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
17
from __future__ import absolute_import
18
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
19
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
20
from .lazy_import import lazy_import
3224.5.31 by Andrew Bennetts
A couple more lazy imports, helps 'bzr log --line -r -1' a little.
21
lazy_import(globals(), """
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
22
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
23
import datetime
5671.1.2 by Jelmer Vernooij
Lazy load gzip (we don't use it when doing 2a), remove some unused imports.
24
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
25
from breezy import (
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
26
    branch as _mod_branch,
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
27
    cache_utf8,
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
28
    osutils,
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
29
    revision,
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
30
    workingtree,
31
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
32
from breezy.i18n import gettext
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
33
""")
34
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
35
from . import (
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
36
    errors,
5685.1.2 by Jelmer Vernooij
Merge bzr.dev.
37
    lazy_regex,
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
38
    registry,
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
39
    trace,
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
40
    )
6695.3.2 by Martin
Fix test fallout from basestring removal
41
from .sixish import (
42
    text_type,
43
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
44
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
45
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
46
class RevisionInfo(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
47
    """The results of applying a revision specification to a branch."""
48
49
    help_txt = """The results of applying a revision specification to a branch.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
50
51
    An instance has two useful attributes: revno, and rev_id.
52
53
    They can also be accessed as spec[0] and spec[1] respectively,
54
    so that you can write code like:
55
    revno, rev_id = RevisionSpec(branch, spec)
56
    although this is probably going to be deprecated later.
57
58
    This class exists mostly to be the return value of a RevisionSpec,
59
    so that you can access the member you're interested in (number or id)
60
    or treat the result as a tuple.
61
    """
62
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
63
    def __init__(self, branch, revno=None, rev_id=None):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
64
        self.branch = branch
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
65
        self._has_revno = (revno is not None)
66
        self._revno = revno
67
        self.rev_id = rev_id
68
        if self.rev_id is None and self._revno is not None:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
69
            # allow caller to be lazy
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
70
            self.rev_id = branch.get_rev_id(self._revno)
71
72
    @property
73
    def revno(self):
74
        if not self._has_revno and self.rev_id is not None:
75
            try:
76
                self._revno = self.branch.revision_id_to_revno(self.rev_id)
77
            except errors.NoSuchRevision:
78
                self._revno = None
79
            self._has_revno = True
80
        return self._revno
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
81
6619.3.20 by Jelmer Vernooij
Apply 2to3 nonzero fix.
82
    def __bool__(self):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
83
        if self.rev_id is None:
84
            return False
85
        # TODO: otherwise, it should depend on how I was built -
86
        # if it's in_history(branch), then check revision_history(),
87
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
88
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
89
6619.3.23 by Jelmer Vernooij
Keep __nonzero__ around for Python2.
90
    __nonzero__ = __bool__
91
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
92
    def __len__(self):
93
        return 2
94
95
    def __getitem__(self, index):
96
        if index == 0: return self.revno
97
        if index == 1: return self.rev_id
98
        raise IndexError(index)
99
100
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
101
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
102
103
    def __eq__(self, other):
104
        if type(other) not in (tuple, list, type(self)):
105
            return False
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
106
        if isinstance(other, type(self)) and self.branch is not other.branch:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
107
            return False
108
        return tuple(self) == tuple(other)
109
110
    def __repr__(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
111
        return '<breezy.revisionspec.RevisionInfo object %s, %s for %r>' % (
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
112
            self.revno, self.rev_id, self.branch)
113
2220.2.3 by Martin Pool
Add tag: revision namespace.
114
    @staticmethod
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
115
    def from_revision_id(branch, revision_id):
2220.2.3 by Martin Pool
Add tag: revision namespace.
116
        """Construct a RevisionInfo given just the id.
117
118
        Use this if you don't know or care what the revno is.
119
        """
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
120
        return RevisionInfo(branch, revno=None, rev_id=revision_id)
2220.2.3 by Martin Pool
Add tag: revision namespace.
121
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
122
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
123
class RevisionSpec(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
124
    """A parsed revision specification."""
125
126
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
127
4569.2.3 by Matthew Fuller
Adjust the help test for the RevisionSpec class a bit to describe the
128
    A revision specification is a string, which may be unambiguous about
129
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
130
    or it may have no prefix, in which case it's tried against several
131
    specifier types in sequence to determine what the user meant.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
132
133
    Revision specs are an UI element, and they have been moved out
134
    of the branch class to leave "back-end" classes unaware of such
135
    details.  Code that gets a revno or rev_id from other code should
136
    not be using revision specs - revnos and revision ids are the
137
    accepted ways to refer to revisions internally.
138
139
    (Equivalent to the old Branch method get_revision_info())
140
    """
141
142
    prefix = None
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
143
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
4569.2.21 by Vincent Ladeuil
Fix some typos.
144
    """Exceptions that RevisionSpec_dwim._match_on will catch.
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
145
4569.2.21 by Vincent Ladeuil
Fix some typos.
146
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
147
    invalid revspec and raises some exception. The exceptions mentioned here
148
    will not be reported to the user but simply ignored without stopping the
149
    dwim processing.
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
150
    """
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
151
152
    @staticmethod
153
    def from_string(spec):
154
        """Parse a revision spec string into a RevisionSpec object.
155
156
        :param spec: A string specified by the user
157
        :return: A RevisionSpec object that understands how to parse the
158
            supplied notation.
159
        """
160
        if spec is None:
161
            return RevisionSpec(None, _internal=True)
6695.3.2 by Martin
Fix test fallout from basestring removal
162
        if not isinstance(spec, (str, text_type)):
163
            raise TypeError("revision spec needs to be text")
3966.2.1 by Jelmer Vernooij
Register revision specifiers in a registry.
164
        match = revspec_registry.get_prefix(spec)
165
        if match is not None:
166
            spectype, specsuffix = match
167
            trace.mutter('Returning RevisionSpec %s for %s',
168
                         spectype.__name__, spec)
169
            return spectype(spec, _internal=True)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
170
        else:
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
171
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
172
            # wait for _match_on to be called.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
173
            return RevisionSpec_dwim(spec, _internal=True)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
174
175
    def __init__(self, spec, _internal=False):
176
        """Create a RevisionSpec referring to the Null revision.
177
178
        :param spec: The original spec supplied by the user
179
        :param _internal: Used to ensure that RevisionSpec is not being
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
180
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
181
        """
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
182
        if not _internal:
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
183
            raise AssertionError(
184
                'Creating a RevisionSpec directly is not supported. '
185
                'Use RevisionSpec.from_string() instead.')
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
186
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
187
        if self.prefix and spec.startswith(self.prefix):
188
            spec = spec[len(self.prefix):]
189
        self.spec = spec
190
191
    def _match_on(self, branch, revs):
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
192
        trace.mutter('Returning RevisionSpec._match_on: None')
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
193
        return RevisionInfo(branch, None, None)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
194
195
    def _match_on_and_check(self, branch, revs):
196
        info = self._match_on(branch, revs)
197
        if info:
198
            return info
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
199
        elif info == (None, None):
200
            # special case - nothing supplied
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
201
            return info
202
        elif self.prefix:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
203
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
204
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
205
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
206
207
    def in_history(self, branch):
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
208
        return self._match_on_and_check(branch, revs=None)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
209
1432 by Robert Collins
branch: namespace
210
        # FIXME: in_history is somewhat broken,
211
        # it will return non-history revisions in many
212
        # circumstances. The expected facility is that
213
        # in_history only returns revision-history revs,
214
        # in_store returns any rev. RBC 20051010
215
    # aliases for now, when we fix the core logic, then they
216
    # will do what you expect.
217
    in_store = in_history
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
218
    in_branch = in_store
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
219
3298.2.4 by John Arbash Meinel
Introduce as_revision_id() as a function instead of in_branch(need_revno=False)
220
    def as_revision_id(self, context_branch):
221
        """Return just the revision_id for this revisions spec.
222
223
        Some revision specs require a context_branch to be able to determine
224
        their value. Not all specs will make use of it.
225
        """
226
        return self._as_revision_id(context_branch)
227
228
    def _as_revision_id(self, context_branch):
229
        """Implementation of as_revision_id()
230
231
        Classes should override this function to provide appropriate
232
        functionality. The default is to just call '.in_history().rev_id'
233
        """
234
        return self.in_history(context_branch).rev_id
235
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
236
    def as_tree(self, context_branch):
237
        """Return the tree object for this revisions spec.
238
239
        Some revision specs require a context_branch to be able to determine
240
        the revision id and access the repository. Not all specs will make
241
        use of it.
242
        """
243
        return self._as_tree(context_branch)
244
245
    def _as_tree(self, context_branch):
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
246
        """Implementation of as_tree().
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
247
248
        Classes should override this function to provide appropriate
249
        functionality. The default is to just call '.as_revision_id()'
250
        and get the revision tree from context_branch's repository.
251
        """
252
        revision_id = self.as_revision_id(context_branch)
253
        return context_branch.repository.revision_tree(revision_id)
254
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
255
    def __repr__(self):
256
        # this is mostly for helping with testing
1948.4.32 by John Arbash Meinel
Clean up __repr__, as well as add tests that we can handle -r12:branch/
257
        return '<%s %s>' % (self.__class__.__name__,
258
                              self.user_spec)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
259
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
260
    def needs_branch(self):
261
        """Whether this revision spec needs a branch.
262
1711.2.99 by John Arbash Meinel
minor typo fix
263
        Set this to False the branch argument of _match_on is not used.
264
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
265
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
266
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
267
    def get_branch(self):
268
        """When the revision specifier contains a branch location, return it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
269
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
270
        Otherwise, return None.
271
        """
272
        return None
273
1907.4.9 by Matthieu Moy
missing newline
274
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
275
# private API
276
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
277
class RevisionSpec_dwim(RevisionSpec):
278
    """Provides a DWIMish revision specifier lookup.
279
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
280
    Note that this does not go in the revspec_registry because by definition
281
    there is no prefix to identify it.  It's solely called from
282
    RevisionSpec.from_string() because the DWIMification happen when _match_on
283
    is called so the string describing the revision is kept here until needed.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
284
    """
285
286
    help_txt = None
287
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
288
    _revno_regex = lazy_regex.lazy_compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
289
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
290
    # The revspecs to try
291
    _possible_revspecs = []
292
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
293
    def _try_spectype(self, rstype, branch):
294
        rs = rstype(self.spec, _internal=True)
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
295
        # Hit in_history to find out if it exists, or we need to try the
296
        # next type.
297
        return rs.in_history(branch)
298
299
    def _match_on(self, branch, revs):
300
        """Run the lookup and see what we can get."""
301
302
        # First, see if it's a revno
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
303
        if self._revno_regex.match(self.spec) is not None:
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
304
            try:
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
305
                return self._try_spectype(RevisionSpec_revno, branch)
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
306
            except RevisionSpec_revno.dwim_catchable_exceptions:
307
                pass
308
309
        # Next see what has been registered
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
310
        for objgetter in self._possible_revspecs:
311
            rs_class = objgetter.get_obj()
312
            try:
313
                return self._try_spectype(rs_class, branch)
314
            except rs_class.dwim_catchable_exceptions:
315
                pass
316
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
317
        # Well, I dunno what it is. Note that we don't try to keep track of the
318
        # first of last exception raised during the DWIM tries as none seems
319
        # really relevant.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
320
        raise errors.InvalidRevisionSpec(self.spec, branch)
321
5671.5.3 by Jelmer Vernooij
Fix test.. not sure how I missed this.
322
    @classmethod
323
    def append_possible_revspec(cls, revspec):
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
324
        """Append a possible DWIM revspec.
325
326
        :param revspec: Revision spec to try.
327
        """
5671.5.3 by Jelmer Vernooij
Fix test.. not sure how I missed this.
328
        cls._possible_revspecs.append(registry._ObjectGetter(revspec))
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
329
5671.5.3 by Jelmer Vernooij
Fix test.. not sure how I missed this.
330
    @classmethod
331
    def append_possible_lazy_revspec(cls, module_name, member_name):
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
332
        """Append a possible lazily loaded DWIM revspec.
333
334
        :param module_name: Name of the module with the revspec
335
        :param member_name: Name of the revspec within the module
336
        """
5671.5.3 by Jelmer Vernooij
Fix test.. not sure how I missed this.
337
        cls._possible_revspecs.append(
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
338
            registry._LazyObjectGetter(module_name, member_name))
339
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
340
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
341
class RevisionSpec_revno(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
342
    """Selects a revision using a number."""
343
344
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
345
346
    Use an integer to specify a revision in the history of the branch.
4569.2.5 by Matthew Fuller
Update online documentation to match new DWIM behavior.
347
    Optionally a branch can be specified.  A negative number will count
348
    from the end of the branch (-1 is the last revision, -2 the previous
349
    one). If the negative number is larger than the branch's history, the
350
    first revision is returned.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
351
    Examples::
352
3651.2.1 by Daniel Clemente
Clarify that you don't have to write a path if you mean the current branch
353
      revno:1                   -> return the first revision of this branch
2023.1.1 by ghigo
add topics help
354
      revno:3:/path/to/branch   -> return the 3rd revision of
355
                                   the branch '/path/to/branch'
356
      revno:-1                  -> The last revision in a branch.
357
      -2:http://other/branch    -> The second to last revision in the
358
                                   remote branch.
359
      -1000000                  -> Most likely the first revision, unless
360
                                   your history is very long.
361
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
362
    prefix = 'revno:'
363
364
    def _match_on(self, branch, revs):
365
        """Lookup a revision by revision number"""
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
366
        branch, revno, revision_id = self._lookup(branch)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
367
        return RevisionInfo(branch, revno, revision_id)
368
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
369
    def _lookup(self, branch):
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
370
        loc = self.spec.find(':')
371
        if loc == -1:
372
            revno_spec = self.spec
373
            branch_spec = None
374
        else:
375
            revno_spec = self.spec[:loc]
376
            branch_spec = self.spec[loc+1:]
377
378
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
379
            if not branch_spec:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
380
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
381
                        branch, 'cannot have an empty revno and no branch')
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
382
            revno = None
383
        else:
384
            try:
385
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
386
                dotted = False
387
            except ValueError:
388
                # dotted decimal. This arguably should not be here
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
389
                # but the from_string method is a little primitive
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
390
                # right now - RBC 20060928
391
                try:
392
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
393
                except ValueError as e:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
394
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
395
396
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
397
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
398
        if branch_spec:
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
399
            # the user has overriden the branch to look in.
400
            branch = _mod_branch.Branch.open(branch_spec)
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
401
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
402
        if dotted:
403
            try:
3949.2.6 by Ian Clatworthy
review feedback from jam
404
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
405
                    _cache_reverse=True)
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
406
            except errors.NoSuchRevision:
3872.2.2 by Marius Kruger
* use NULL_REVISION in stead of None for rev_id
407
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
408
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
409
                # there is no traditional 'revno' for dotted-decimal revnos.
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
410
                # so for API compatibility we return None.
3949.2.6 by Ian Clatworthy
review feedback from jam
411
                return branch, None, revision_id
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
412
        else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
413
            last_revno, last_revision_id = branch.last_revision_info()
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
414
            if revno < 0:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
415
                # if get_rev_id supported negative revnos, there would not be a
416
                # need for this special case.
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
417
                if (-revno) >= last_revno:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
418
                    revno = 1
419
                else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
420
                    revno = last_revno + revno + 1
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
421
            try:
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
422
                revision_id = branch.get_rev_id(revno)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
423
            except errors.NoSuchRevision:
424
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
425
        return branch, revno, revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
426
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
427
    def _as_revision_id(self, context_branch):
428
        # We would have the revno here, but we don't really care
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
429
        branch, revno, revision_id = self._lookup(context_branch)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
430
        return revision_id
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
431
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
432
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
433
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
434
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
435
    def get_branch(self):
436
        if self.spec.find(':') == -1:
437
            return None
438
        else:
439
            return self.spec[self.spec.find(':')+1:]
440
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
441
# Old compatibility
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
442
RevisionSpec_int = RevisionSpec_revno
443
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
444
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
445
class RevisionIDSpec(RevisionSpec):
446
447
    def _match_on(self, branch, revs):
448
        revision_id = self.as_revision_id(branch)
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
449
        return RevisionInfo.from_revision_id(branch, revision_id)
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
450
451
452
class RevisionSpec_revid(RevisionIDSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
453
    """Selects a revision using the revision id."""
454
455
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
456
457
    Supply a specific revision id, that can be used to specify any
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
458
    revision id in the ancestry of the branch.
2023.1.1 by ghigo
add topics help
459
    Including merges, and pending merges.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
460
    Examples::
461
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
462
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
463
    """
464
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
465
    prefix = 'revid:'
466
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
467
    def _as_revision_id(self, context_branch):
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
468
        # self.spec comes straight from parsing the command line arguments,
469
        # so we expect it to be a Unicode string. Switch it to the internal
470
        # representation.
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
471
        if isinstance(self.spec, unicode):
472
            return cache_utf8.encode(self.spec)
473
        return self.spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
474
475
476
477
class RevisionSpec_last(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
478
    """Selects the nth revision from the end."""
479
480
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
481
482
    Supply a positive number to get the nth revision from the end.
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
483
    This is the same as supplying negative numbers to the 'revno:' spec.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
484
    Examples::
485
2023.1.1 by ghigo
add topics help
486
      last:1        -> return the last revision
487
      last:3        -> return the revision 2 before the end.
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
488
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
489
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
490
    prefix = 'last:'
491
492
    def _match_on(self, branch, revs):
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
493
        revno, revision_id = self._revno_and_revision_id(branch)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
494
        return RevisionInfo(branch, revno, revision_id)
495
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
496
    def _revno_and_revision_id(self, context_branch):
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
497
        last_revno, last_revision_id = context_branch.last_revision_info()
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
498
1948.4.9 by John Arbash Meinel
Cleanup and test last:
499
        if self.spec == '':
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
500
            if not last_revno:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
501
                raise errors.NoCommits(context_branch)
502
            return last_revno, last_revision_id
1948.4.9 by John Arbash Meinel
Cleanup and test last:
503
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
504
        try:
505
            offset = int(self.spec)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
506
        except ValueError as e:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
507
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
508
509
        if offset <= 0:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
510
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
511
                                             'you must supply a positive value')
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
512
513
        revno = last_revno - offset + 1
1948.4.9 by John Arbash Meinel
Cleanup and test last:
514
        try:
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
515
            revision_id = context_branch.get_rev_id(revno)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
516
        except errors.NoSuchRevision:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
517
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
518
        return revno, revision_id
519
520
    def _as_revision_id(self, context_branch):
521
        # We compute the revno as part of the process, but we don't really care
522
        # about it.
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
523
        revno, revision_id = self._revno_and_revision_id(context_branch)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
524
        return revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
525
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
526
527
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
528
class RevisionSpec_before(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
529
    """Selects the parent of the revision specified."""
530
531
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
532
3651.2.4 by Daniel Clemente
Reordered to put explanation first and exceptions after
533
    Supply any revision spec to return the parent of that revision.  This is
534
    mostly useful when inspecting revisions that are not in the revision history
535
    of a branch.
536
2023.1.1 by ghigo
add topics help
537
    It is an error to request the parent of the null revision (before:0).
538
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
539
    Examples::
540
2023.1.1 by ghigo
add topics help
541
      before:1913    -> Return the parent of revno 1913 (revno 1912)
542
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
543
                                            aaaa@bbbb-1234567890
3651.2.5 by Daniel Clemente
Wrote specifical and simpler example for 'before:', and referred to 'bzr diff -c'
544
      bzr diff -r before:1913..1913
545
            -> Find the changes between revision 1913 and its parent (1912).
546
               (What changes did revision 1913 introduce).
547
               This is equivalent to:  bzr diff -c 1913
2023.1.1 by ghigo
add topics help
548
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
549
550
    prefix = 'before:'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
551
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
552
    def _match_on(self, branch, revs):
553
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
554
        if r.revno == 0:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
555
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
556
                                         'cannot go before the null: revision')
557
        if r.revno is None:
558
            # We need to use the repository history here
559
            rev = branch.repository.get_revision(r.rev_id)
560
            if not rev.parent_ids:
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
561
                revision_id = revision.NULL_REVISION
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
562
            else:
563
                revision_id = rev.parent_ids[0]
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
564
            revno = None
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
565
        else:
566
            revno = r.revno - 1
567
            try:
568
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
569
            except errors.NoSuchRevision:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
570
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
571
                                                 branch)
572
        return RevisionInfo(branch, revno, revision_id)
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
573
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
574
    def _as_revision_id(self, context_branch):
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
575
        base_revision_id = RevisionSpec.from_string(self.spec)._as_revision_id(context_branch)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
576
        if base_revision_id == revision.NULL_REVISION:
3495.1.1 by John Arbash Meinel
Fix bug #239933, use the right exception for -c0
577
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
578
                                         'cannot go before the null: revision')
3298.2.10 by Aaron Bentley
Refactor partial history code
579
        context_repo = context_branch.repository
580
        context_repo.lock_read()
581
        try:
582
            parent_map = context_repo.get_parent_map([base_revision_id])
583
        finally:
584
            context_repo.unlock()
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
585
        if base_revision_id not in parent_map:
586
            # Ghost, or unknown revision id
587
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
588
                'cannot find the matching revision')
589
        parents = parent_map[base_revision_id]
590
        if len(parents) < 1:
591
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
592
                'No parents for revision.')
593
        return parents[0]
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
594
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
595
596
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
597
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
598
    """Select a revision identified by tag name"""
599
600
    help_txt = """Selects a revision identified by a tag name.
601
1551.10.34 by Aaron Bentley
Fix tag: help
602
    Tags are stored in the branch and created by the 'tag' command.
2220.2.3 by Martin Pool
Add tag: revision namespace.
603
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
604
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
605
    prefix = 'tag:'
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
606
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
607
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
608
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
609
        # Can raise tags not supported, NoSuchTag, etc
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
610
        return RevisionInfo.from_revision_id(branch,
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
611
            branch.tags.lookup_tag(self.spec))
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
612
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
613
    def _as_revision_id(self, context_branch):
614
        return context_branch.tags.lookup_tag(self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
615
616
617
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
618
class _RevListToTimestamps(object):
619
    """This takes a list of revisions, and allows you to bisect by date"""
620
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
621
    __slots__ = ['branch']
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
622
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
623
    def __init__(self, branch):
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
624
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
625
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
626
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
627
        """Get the date of the index'd item"""
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
628
        r = self.branch.repository.get_revision(self.branch.get_rev_id(index))
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
629
        # TODO: Handle timezone.
630
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
631
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
632
    def __len__(self):
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
633
        return self.branch.revno()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
634
635
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
636
class RevisionSpec_date(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
637
    """Selects a revision on the basis of a datestamp."""
638
639
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
640
641
    Supply a datestamp to select the first revision that matches the date.
642
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
643
    Matches the first entry after a given date (either at midnight or
644
    at a specified time).
645
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
646
    One way to display all the changes since yesterday would be::
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
647
6622.1.30 by Jelmer Vernooij
Some more test fixes.
648
        brz log -r date:yesterday..
2023.1.1 by ghigo
add topics help
649
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
650
    Examples::
651
2023.1.1 by ghigo
add topics help
652
      date:yesterday            -> select the first revision since yesterday
653
      date:2006-08-14,17:10:14  -> select the first revision after
654
                                   August 14th, 2006 at 5:10pm.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
655
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
656
    prefix = 'date:'
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
657
    _date_regex = lazy_regex.lazy_compile(
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
658
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
659
            r'(,|T)?\s*'
660
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
661
        )
662
663
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
664
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
665
          date:value
666
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
667
          matches the first entry after a given date (either at midnight or
668
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
669
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
670
        #  XXX: This doesn't actually work
671
        #  So the proper way of saying 'give me all entries for today' is:
672
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
673
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
674
        if self.spec.lower() == 'yesterday':
675
            dt = today - datetime.timedelta(days=1)
676
        elif self.spec.lower() == 'today':
677
            dt = today
678
        elif self.spec.lower() == 'tomorrow':
679
            dt = today + datetime.timedelta(days=1)
680
        else:
5685.1.1 by Jelmer Vernooij
More lazy imports, lazy regexes in bzrlib.revisionspec.
681
            m = self._date_regex.match(self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
682
            if not m or (not m.group('date') and not m.group('time')):
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
683
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
684
                                                 branch, 'invalid date')
685
686
            try:
687
                if m.group('date'):
688
                    year = int(m.group('year'))
689
                    month = int(m.group('month'))
690
                    day = int(m.group('day'))
691
                else:
692
                    year = today.year
693
                    month = today.month
694
                    day = today.day
695
696
                if m.group('time'):
697
                    hour = int(m.group('hour'))
698
                    minute = int(m.group('minute'))
699
                    if m.group('second'):
700
                        second = int(m.group('second'))
701
                    else:
702
                        second = 0
703
                else:
704
                    hour, minute, second = 0,0,0
705
            except ValueError:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
706
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
707
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
708
709
            dt = datetime.datetime(year=year, month=month, day=day,
710
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
711
        branch.lock_read()
712
        try:
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
713
            rev = bisect.bisect(_RevListToTimestamps(branch), dt, 1)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
714
        finally:
715
            branch.unlock()
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
716
        if rev == branch.revno():
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
717
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
718
        return RevisionInfo(branch, rev)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
719
720
721
722
class RevisionSpec_ancestor(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
723
    """Selects a common ancestor with a second branch."""
724
725
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
726
727
    Supply the path to a branch to select the common ancestor.
728
729
    The common ancestor is the last revision that existed in both
730
    branches. Usually this is the branch point, but it could also be
731
    a revision that was merged.
732
733
    This is frequently used with 'diff' to return all of the changes
734
    that your branch introduces, while excluding the changes that you
735
    have not merged from the remote branch.
736
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
737
    Examples::
738
2023.1.1 by ghigo
add topics help
739
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
740
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
741
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
742
    prefix = 'ancestor:'
743
744
    def _match_on(self, branch, revs):
1551.10.33 by Aaron Bentley
Updates from review
745
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
746
        return self._find_revision_info(branch, self.spec)
747
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
748
    def _as_revision_id(self, context_branch):
749
        return self._find_revision_id(context_branch, self.spec)
750
1551.10.33 by Aaron Bentley
Updates from review
751
    @staticmethod
752
    def _find_revision_info(branch, other_location):
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
753
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
754
                                                              other_location)
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
755
        return RevisionInfo(branch, None, revision_id)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
756
757
    @staticmethod
758
    def _find_revision_id(branch, other_location):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
759
        from .branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
760
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
761
        branch.lock_read()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
762
        try:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
763
            revision_a = revision.ensure_null(branch.last_revision())
764
            if revision_a == revision.NULL_REVISION:
765
                raise errors.NoCommits(branch)
3984.1.2 by Daniel Watkins
Added fix.
766
            if other_location == '':
767
                other_location = branch.get_parent()
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
768
            other_branch = Branch.open(other_location)
769
            other_branch.lock_read()
770
            try:
771
                revision_b = revision.ensure_null(other_branch.last_revision())
772
                if revision_b == revision.NULL_REVISION:
773
                    raise errors.NoCommits(other_branch)
774
                graph = branch.repository.get_graph(other_branch.repository)
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
775
                rev_id = graph.find_unique_lca(revision_a, revision_b)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
776
            finally:
777
                other_branch.unlock()
778
            if rev_id == revision.NULL_REVISION:
779
                raise errors.NoCommonAncestor(revision_a, revision_b)
780
            return rev_id
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
781
        finally:
782
            branch.unlock()
1551.10.33 by Aaron Bentley
Updates from review
783
784
1432 by Robert Collins
branch: namespace
785
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
786
1432 by Robert Collins
branch: namespace
787
class RevisionSpec_branch(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
788
    """Selects the last revision of a specified branch."""
789
790
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
791
792
    Supply the path to a branch to select its last revision.
793
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
794
    Examples::
795
2023.1.1 by ghigo
add topics help
796
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
797
    """
798
    prefix = 'branch:'
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
799
    dwim_catchable_exceptions = (errors.NotBranchError,)
1432 by Robert Collins
branch: namespace
800
801
    def _match_on(self, branch, revs):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
802
        from .branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
803
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
804
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
805
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
806
            raise errors.NoCommits(other_branch)
5318.1.1 by Martin von Gagern
Extract branch location from branch: revision specs.
807
        if branch is None:
808
            branch = other_branch
809
        else:
810
            try:
811
                # pull in the remote revisions so we can diff
812
                branch.fetch(other_branch, revision_b)
813
            except errors.ReadOnlyError:
814
                branch = other_branch
6336.1.1 by Jelmer Vernooij
Deprecate ``RevisionSpec.wants_revision_history`` and remove any uses of it.
815
        return RevisionInfo(branch, None, revision_b)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
816
817
    def _as_revision_id(self, context_branch):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
818
        from .branch import Branch
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
819
        other_branch = Branch.open(self.spec)
820
        last_revision = other_branch.last_revision()
821
        last_revision = revision.ensure_null(last_revision)
1551.19.33 by Aaron Bentley
Use as_revision_id for diff
822
        context_branch.fetch(other_branch, last_revision)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
823
        if last_revision == revision.NULL_REVISION:
824
            raise errors.NoCommits(other_branch)
825
        return last_revision
826
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
827
    def _as_tree(self, context_branch):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
828
        from .branch import Branch
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
829
        other_branch = Branch.open(self.spec)
830
        last_revision = other_branch.last_revision()
831
        last_revision = revision.ensure_null(last_revision)
832
        if last_revision == revision.NULL_REVISION:
833
            raise errors.NoCommits(other_branch)
834
        return other_branch.repository.revision_tree(last_revision)
835
5318.1.1 by Martin von Gagern
Extract branch location from branch: revision specs.
836
    def needs_branch(self):
837
        return False
838
839
    def get_branch(self):
840
        return self.spec
841
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
842
843
1551.10.33 by Aaron Bentley
Updates from review
844
class RevisionSpec_submit(RevisionSpec_ancestor):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
845
    """Selects a common ancestor with a submit branch."""
846
847
    help_txt = """Selects a common ancestor with the submit branch.
848
849
    Diffing against this shows all the changes that were made in this branch,
850
    and is a good predictor of what merge will do.  The submit branch is
3565.2.1 by Christophe Troestler
(trivial) Corrected typos.
851
    used by the bundle and merge directive commands.  If no submit branch
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
852
    is specified, the parent branch is used instead.
853
854
    The common ancestor is the last revision that existed in both
855
    branches. Usually this is the branch point, but it could also be
856
    a revision that was merged.
857
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
858
    Examples::
859
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
860
      $ bzr diff -r submit:
861
    """
1551.10.33 by Aaron Bentley
Updates from review
862
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
863
    prefix = 'submit:'
864
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
865
    def _get_submit_location(self, branch):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
866
        submit_location = branch.get_submit_branch()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
867
        location_type = 'submit branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
868
        if submit_location is None:
869
            submit_location = branch.get_parent()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
870
            location_type = 'parent branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
871
        if submit_location is None:
872
            raise errors.NoSubmitBranch(branch)
6147.1.1 by Jonathan Riddell
use .format() instead of % for string formatting where there are multiple formats in one string to allow for translations
873
        trace.note(gettext('Using {0} {1}').format(location_type,
874
                                                        submit_location))
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
875
        return submit_location
876
877
    def _match_on(self, branch, revs):
878
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
879
        return self._find_revision_info(branch,
880
            self._get_submit_location(branch))
881
882
    def _as_revision_id(self, context_branch):
883
        return self._find_revision_id(context_branch,
884
            self._get_submit_location(context_branch))
1551.10.33 by Aaron Bentley
Updates from review
885
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
886
5365.6.6 by Aaron Bentley
Implement 'annotate' revision-id.
887
class RevisionSpec_annotate(RevisionIDSpec):
888
889
    prefix = 'annotate:'
890
891
    help_txt = """Select the revision that last modified the specified line.
892
893
    Select the revision that last modified the specified line.  Line is
894
    specified as path:number.  Path is a relative path to the file.  Numbers
895
    start at 1, and are relative to the current version, not the last-
896
    committed version of the file.
897
    """
898
899
    def _raise_invalid(self, numstring, context_branch):
900
        raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
901
            'No such line: %s' % numstring)
902
903
    def _as_revision_id(self, context_branch):
904
        path, numstring = self.spec.rsplit(':', 1)
905
        try:
906
            index = int(numstring) - 1
907
        except ValueError:
908
            self._raise_invalid(numstring, context_branch)
909
        tree, file_path = workingtree.WorkingTree.open_containing(path)
910
        tree.lock_read()
911
        try:
912
            file_id = tree.path2id(file_path)
913
            if file_id is None:
914
                raise errors.InvalidRevisionSpec(self.user_spec,
915
                    context_branch, "File '%s' is not versioned." %
916
                    file_path)
917
            revision_ids = [r for (r, l) in tree.annotate_iter(file_id)]
918
        finally:
919
            tree.unlock()
920
        try:
921
            revision_id = revision_ids[index]
922
        except IndexError:
923
            self._raise_invalid(numstring, context_branch)
924
        if revision_id == revision.CURRENT_REVISION:
925
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
926
                'Line %s has not been committed.' % numstring)
927
        return revision_id
928
929
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
930
class RevisionSpec_mainline(RevisionIDSpec):
931
932
    help_txt = """Select mainline revision that merged the specified revision.
933
934
    Select the revision that merged the specified revision into mainline.
935
    """
936
937
    prefix = 'mainline:'
938
939
    def _as_revision_id(self, context_branch):
940
        revspec = RevisionSpec.from_string(self.spec)
941
        if revspec.get_branch() is None:
942
            spec_branch = context_branch
943
        else:
944
            spec_branch = _mod_branch.Branch.open(revspec.get_branch())
945
        revision_id = revspec.as_revision_id(spec_branch)
946
        graph = context_branch.repository.get_graph()
947
        result = graph.find_lefthand_merger(revision_id,
948
                                            context_branch.last_revision())
949
        if result is None:
950
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
951
        return result
952
953
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
954
# The order in which we want to DWIM a revision spec without any prefix.
955
# revno is always tried first and isn't listed here, this is used by
956
# RevisionSpec_dwim._match_on
5671.5.1 by Jelmer Vernooij
Allow lazily registering possible DWIM revspecs.
957
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
958
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
959
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
960
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
961
3966.2.1 by Jelmer Vernooij
Register revision specifiers in a registry.
962
revspec_registry = registry.Registry()
963
def _register_revspec(revspec):
964
    revspec_registry.register(revspec.prefix, revspec)
965
966
_register_revspec(RevisionSpec_revno)
967
_register_revspec(RevisionSpec_revid)
968
_register_revspec(RevisionSpec_last)
969
_register_revspec(RevisionSpec_before)
970
_register_revspec(RevisionSpec_tag)
971
_register_revspec(RevisionSpec_date)
972
_register_revspec(RevisionSpec_ancestor)
973
_register_revspec(RevisionSpec_branch)
974
_register_revspec(RevisionSpec_submit)
5365.6.6 by Aaron Bentley
Implement 'annotate' revision-id.
975
_register_revspec(RevisionSpec_annotate)
5365.6.4 by Aaron Bentley
Implement mainline revision spec.
976
_register_revspec(RevisionSpec_mainline)