~bzr-pqm/bzr/bzr.dev

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