~bzr-pqm/bzr/bzr.dev

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