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