~bzr-pqm/bzr/bzr.dev

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