~bzr-pqm/bzr/bzr.dev

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