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