/brz/remove-bazaar

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