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