/brz/remove-bazaar

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