/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)
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
61
        elif rev_id is None:
62
            self.rev_id = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
63
        else:
64
            self.rev_id = rev_id
65
66
    def __nonzero__(self):
67
        # first the easy ones...
68
        if self.rev_id is None:
69
            return False
70
        if self.revno is not None:
71
            return True
72
        # TODO: otherwise, it should depend on how I was built -
73
        # if it's in_history(branch), then check revision_history(),
74
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
75
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
76
77
    def __len__(self):
78
        return 2
79
80
    def __getitem__(self, index):
81
        if index == 0: return self.revno
82
        if index == 1: return self.rev_id
83
        raise IndexError(index)
84
85
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
86
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
87
88
    def __eq__(self, other):
89
        if type(other) not in (tuple, list, type(self)):
90
            return False
91
        if type(other) is type(self) and self.branch is not other.branch:
92
            return False
93
        return tuple(self) == tuple(other)
94
95
    def __repr__(self):
96
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
97
            self.revno, self.rev_id, self.branch)
98
2220.2.3 by Martin Pool
Add tag: revision namespace.
99
    @staticmethod
100
    def from_revision_id(branch, revision_id, revs):
101
        """Construct a RevisionInfo given just the id.
102
103
        Use this if you don't know or care what the revno is.
104
        """
105
        try:
106
            revno = revs.index(revision_id) + 1
107
        except ValueError:
108
            revno = None
109
        return RevisionInfo(branch, revno, revision_id)
110
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
111
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
112
# classes in this list should have a "prefix" attribute, against which
113
# string specs are matched
114
SPEC_TYPES = []
1948.4.35 by John Arbash Meinel
Move the _revno_regex to a more logical location
115
_revno_regex = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
116
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
117
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
118
class RevisionSpec(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
119
    """A parsed revision specification."""
120
121
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
122
123
    A revision specification can be an integer, in which case it is
124
    assumed to be a revno (though this will translate negative values
125
    into positive ones); or it can be a string, in which case it is
126
    parsed for something like 'date:' or 'revid:' etc.
127
128
    Revision specs are an UI element, and they have been moved out
129
    of the branch class to leave "back-end" classes unaware of such
130
    details.  Code that gets a revno or rev_id from other code should
131
    not be using revision specs - revnos and revision ids are the
132
    accepted ways to refer to revisions internally.
133
134
    (Equivalent to the old Branch method get_revision_info())
135
    """
136
137
    prefix = None
138
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
139
    def __new__(cls, spec, _internal=False):
140
        if _internal:
141
            return object.__new__(cls, spec, _internal=_internal)
142
143
        symbol_versioning.warn('Creating a RevisionSpec directly has'
144
                               ' been deprecated in version 0.11. Use'
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
145
                               ' RevisionSpec.from_string()'
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
146
                               ' instead.',
147
                               DeprecationWarning, stacklevel=2)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
148
        return RevisionSpec.from_string(spec)
149
150
    @staticmethod
151
    def from_string(spec):
152
        """Parse a revision spec string into a RevisionSpec object.
153
154
        :param spec: A string specified by the user
155
        :return: A RevisionSpec object that understands how to parse the
156
            supplied notation.
157
        """
158
        if not isinstance(spec, (type(None), basestring)):
159
            raise TypeError('error')
160
161
        if spec is None:
162
            return RevisionSpec(None, _internal=True)
163
164
        assert isinstance(spec, basestring), \
165
            "You should only supply strings not %s" % (type(spec),)
166
167
        for spectype in SPEC_TYPES:
168
            if spec.startswith(spectype.prefix):
169
                trace.mutter('Returning RevisionSpec %s for %s',
170
                             spectype.__name__, spec)
171
                return spectype(spec, _internal=True)
172
        else:
173
            # RevisionSpec_revno is special cased, because it is the only
174
            # one that directly handles plain integers
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
175
            # TODO: This should not be special cased rather it should be
176
            # 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)
177
            global _revno_regex
178
            if _revno_regex is None:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
179
                _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)
180
            if _revno_regex.match(spec) is not None:
181
                return RevisionSpec_revno(spec, _internal=True)
182
183
            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
184
185
    def __init__(self, spec, _internal=False):
186
        """Create a RevisionSpec referring to the Null revision.
187
188
        :param spec: The original spec supplied by the user
189
        :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)
190
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
191
        """
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
192
        if not _internal:
193
            # XXX: Update this after 0.10 is released
194
            symbol_versioning.warn('Creating a RevisionSpec directly has'
195
                                   ' 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)
196
                                   ' 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
197
                                   ' instead.',
198
                                   DeprecationWarning, stacklevel=2)
199
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
200
        if self.prefix and spec.startswith(self.prefix):
201
            spec = spec[len(self.prefix):]
202
        self.spec = spec
203
204
    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
205
        trace.mutter('Returning RevisionSpec._match_on: None')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
206
        return RevisionInfo(branch, 0, None)
207
208
    def _match_on_and_check(self, branch, revs):
209
        info = self._match_on(branch, revs)
210
        if info:
211
            return info
212
        elif info == (0, None):
213
            # special case - the empty tree
214
            return info
215
        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
216
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
217
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
218
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
219
220
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
221
        if branch:
222
            revs = branch.revision_history()
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
237
    in_branch = in_store
238
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
239
    def __repr__(self):
240
        # 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/
241
        return '<%s %s>' % (self.__class__.__name__,
242
                              self.user_spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
243
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
244
    def needs_branch(self):
245
        """Whether this revision spec needs a branch.
246
1711.2.99 by John Arbash Meinel
minor typo fix
247
        Set this to False the branch argument of _match_on is not used.
248
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
249
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
250
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
251
    def get_branch(self):
252
        """When the revision specifier contains a branch location, return it.
253
        
254
        Otherwise, return None.
255
        """
256
        return None
257
1907.4.9 by Matthieu Moy
missing newline
258
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
259
# private API
260
261
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
262
    """Selects a revision using a number."""
263
264
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
265
266
    Use an integer to specify a revision in the history of the branch.
267
    Optionally a branch can be specified. The 'revno:' prefix is optional.
268
    A negative number will count from the end of the branch (-1 is the
269
    last revision, -2 the previous one). If the negative number is larger
270
    than the branch's history, the first revision is returned.
271
    examples:
272
      revno:1                   -> return the first revision
273
      revno:3:/path/to/branch   -> return the 3rd revision of
274
                                   the branch '/path/to/branch'
275
      revno:-1                  -> The last revision in a branch.
276
      -2:http://other/branch    -> The second to last revision in the
277
                                   remote branch.
278
      -1000000                  -> Most likely the first revision, unless
279
                                   your history is very long.
280
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
281
    prefix = 'revno:'
282
283
    def _match_on(self, branch, revs):
284
        """Lookup a revision by revision number"""
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
285
        loc = self.spec.find(':')
286
        if loc == -1:
287
            revno_spec = self.spec
288
            branch_spec = None
289
        else:
290
            revno_spec = self.spec[:loc]
291
            branch_spec = self.spec[loc+1:]
292
293
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
294
            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
295
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
296
                        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
297
            revno = None
298
        else:
299
            try:
300
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
301
                dotted = False
302
            except ValueError:
303
                # dotted decimal. This arguably should not be here
304
                # but the from_string method is a little primitive 
305
                # right now - RBC 20060928
306
                try:
307
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
308
                except ValueError, e:
309
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
310
311
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
312
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
313
        if branch_spec:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
314
            # the user has override the branch to look in.
315
            # we need to refresh the revision_history map and
316
            # the branch object.
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
317
            from bzrlib.branch import Branch
318
            branch = Branch.open(branch_spec)
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
319
            # Need to use a new revision history
320
            # because we are using a specific branch
321
            revs = branch.revision_history()
322
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
323
        if dotted:
324
            branch.lock_read()
325
            try:
2418.5.9 by John Arbash Meinel
Have RevisionSpec_revno() also use the new helper
326
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
327
                revisions = [revision_id for revision_id, revno
328
                             in revision_id_to_revno.iteritems()
329
                             if revno == match_revno]
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
330
            finally:
331
                branch.unlock()
332
            if len(revisions) != 1:
333
                return RevisionInfo(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
334
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
335
                # there is no traditional 'revno' for dotted-decimal revnos.
336
                # so for  API compatability we return None.
2418.5.9 by John Arbash Meinel
Have RevisionSpec_revno() also use the new helper
337
                return RevisionInfo(branch, None, revisions[0])
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
338
        else:
339
            if revno < 0:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
340
                # if get_rev_id supported negative revnos, there would not be a
341
                # need for this special case.
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
342
                if (-revno) >= len(revs):
343
                    revno = 1
344
                else:
345
                    revno = len(revs) + revno + 1
346
            try:
347
                revision_id = branch.get_rev_id(revno, revs)
348
            except errors.NoSuchRevision:
349
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
350
        return RevisionInfo(branch, revno, revision_id)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
351
        
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
352
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
353
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
354
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
355
    def get_branch(self):
356
        if self.spec.find(':') == -1:
357
            return None
358
        else:
359
            return self.spec[self.spec.find(':')+1:]
360
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
361
# Old compatibility 
362
RevisionSpec_int = RevisionSpec_revno
363
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
364
SPEC_TYPES.append(RevisionSpec_revno)
365
366
367
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
368
    """Selects a revision using the revision id."""
369
370
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
371
372
    Supply a specific revision id, that can be used to specify any
373
    revision id in the ancestry of the branch. 
374
    Including merges, and pending merges.
375
    examples:
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
376
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
2023.1.1 by ghigo
add topics help
377
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
378
    prefix = 'revid:'
379
380
    def _match_on(self, branch, revs):
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
381
        # self.spec comes straight from parsing the command line arguments,
382
        # so we expect it to be a Unicode string. Switch it to the internal
383
        # representation.
384
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
2325.2.3 by Marien Zwart
Make the revid RevisionSpec also support utf8-encoded bytestrings.
385
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
386
387
SPEC_TYPES.append(RevisionSpec_revid)
388
389
390
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
391
    """Selects the nth revision from the end."""
392
393
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
394
395
    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
396
    This is the same as supplying negative numbers to the 'revno:' spec.
2023.1.1 by ghigo
add topics help
397
    examples:
398
      last:1        -> return the last revision
399
      last:3        -> return the revision 2 before the end.
400
    """    
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
401
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
402
    prefix = 'last:'
403
404
    def _match_on(self, branch, revs):
1948.4.9 by John Arbash Meinel
Cleanup and test last:
405
        if self.spec == '':
406
            if not revs:
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
407
                raise errors.NoCommits(branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
408
            return RevisionInfo(branch, len(revs), revs[-1])
409
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
410
        try:
411
            offset = int(self.spec)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
412
        except ValueError, e:
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
413
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
414
415
        if offset <= 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
416
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
417
                                             'you must supply a positive value')
418
        revno = len(revs) - offset + 1
419
        try:
420
            revision_id = branch.get_rev_id(revno, revs)
421
        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
422
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
423
        return RevisionInfo(branch, revno, revision_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
424
425
SPEC_TYPES.append(RevisionSpec_last)
426
427
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
428
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
429
    """Selects the parent of the revision specified."""
430
431
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
432
433
    Supply any revision spec to return the parent of that revision.
434
    It is an error to request the parent of the null revision (before:0).
435
    This is mostly useful when inspecting revisions that are not in the
436
    revision history of a branch.
437
438
    examples:
439
      before:1913    -> Return the parent of revno 1913 (revno 1912)
440
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
441
                                            aaaa@bbbb-1234567890
2023.1.1 by ghigo
add topics help
442
      bzr diff -r before:revid:aaaa..revid:aaaa
443
            -> Find the changes between revision 'aaaa' and its parent.
444
               (what changes did 'aaaa' introduce)
445
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
446
447
    prefix = 'before:'
448
    
449
    def _match_on(self, branch, revs):
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
450
        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
451
        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
452
            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
453
                                         'cannot go before the null: revision')
454
        if r.revno is None:
455
            # We need to use the repository history here
456
            rev = branch.repository.get_revision(r.rev_id)
457
            if not rev.parent_ids:
458
                revno = 0
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
459
                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
460
            else:
461
                revision_id = rev.parent_ids[0]
462
                try:
463
                    revno = revs.index(revision_id) + 1
464
                except ValueError:
465
                    revno = None
466
        else:
467
            revno = r.revno - 1
468
            try:
469
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
470
            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
471
                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
472
                                                 branch)
473
        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
474
475
SPEC_TYPES.append(RevisionSpec_before)
476
477
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
478
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
479
    """Select a revision identified by tag name"""
480
481
    help_txt = """Selects a revision identified by a tag name.
482
1551.10.34 by Aaron Bentley
Fix tag: help
483
    Tags are stored in the branch and created by the 'tag' command.
2220.2.3 by Martin Pool
Add tag: revision namespace.
484
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
485
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
486
    prefix = 'tag:'
487
488
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
489
        # Can raise tags not supported, NoSuchTag, etc
490
        return RevisionInfo.from_revision_id(branch,
2220.2.20 by Martin Pool
Tag methods now available through Branch.tags.add_tag, etc
491
            branch.tags.lookup_tag(self.spec),
2220.2.3 by Martin Pool
Add tag: revision namespace.
492
            revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
493
494
SPEC_TYPES.append(RevisionSpec_tag)
495
496
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
497
class _RevListToTimestamps(object):
498
    """This takes a list of revisions, and allows you to bisect by date"""
499
500
    __slots__ = ['revs', 'branch']
501
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
502
    def __init__(self, revs, branch):
503
        self.revs = revs
504
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
505
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
506
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
507
        """Get the date of the index'd item"""
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
508
        r = self.branch.repository.get_revision(self.revs[index])
509
        # TODO: Handle timezone.
510
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
511
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
512
    def __len__(self):
513
        return len(self.revs)
514
515
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
516
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
517
    """Selects a revision on the basis of a datestamp."""
518
519
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
520
521
    Supply a datestamp to select the first revision that matches the date.
522
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
523
    Matches the first entry after a given date (either at midnight or
524
    at a specified time).
525
526
    One way to display all the changes since yesterday would be:
527
        bzr log -r date:yesterday..-1
528
529
    examples:
530
      date:yesterday            -> select the first revision since yesterday
531
      date:2006-08-14,17:10:14  -> select the first revision after
532
                                   August 14th, 2006 at 5:10pm.
533
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
534
    prefix = 'date:'
535
    _date_re = re.compile(
536
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
537
            r'(,|T)?\s*'
538
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
539
        )
540
541
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
542
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
543
          date:value
544
          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
545
          matches the first entry after a given date (either at midnight or
546
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
547
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
548
        #  XXX: This doesn't actually work
549
        #  So the proper way of saying 'give me all entries for today' is:
550
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
551
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
552
        if self.spec.lower() == 'yesterday':
553
            dt = today - datetime.timedelta(days=1)
554
        elif self.spec.lower() == 'today':
555
            dt = today
556
        elif self.spec.lower() == 'tomorrow':
557
            dt = today + datetime.timedelta(days=1)
558
        else:
559
            m = self._date_re.match(self.spec)
560
            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
561
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
562
                                                 branch, 'invalid date')
563
564
            try:
565
                if m.group('date'):
566
                    year = int(m.group('year'))
567
                    month = int(m.group('month'))
568
                    day = int(m.group('day'))
569
                else:
570
                    year = today.year
571
                    month = today.month
572
                    day = today.day
573
574
                if m.group('time'):
575
                    hour = int(m.group('hour'))
576
                    minute = int(m.group('minute'))
577
                    if m.group('second'):
578
                        second = int(m.group('second'))
579
                    else:
580
                        second = 0
581
                else:
582
                    hour, minute, second = 0,0,0
583
            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
584
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
585
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
586
587
            dt = datetime.datetime(year=year, month=month, day=day,
588
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
589
        branch.lock_read()
590
        try:
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
591
            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)
592
        finally:
593
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
594
        if rev == len(revs):
595
            return RevisionInfo(branch, None)
596
        else:
597
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
598
599
SPEC_TYPES.append(RevisionSpec_date)
600
601
602
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
603
    """Selects a common ancestor with a second branch."""
604
605
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
606
607
    Supply the path to a branch to select the common ancestor.
608
609
    The common ancestor is the last revision that existed in both
610
    branches. Usually this is the branch point, but it could also be
611
    a revision that was merged.
612
613
    This is frequently used with 'diff' to return all of the changes
614
    that your branch introduces, while excluding the changes that you
615
    have not merged from the remote branch.
616
617
    examples:
618
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
619
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
620
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
621
    prefix = 'ancestor:'
622
623
    def _match_on(self, branch, revs):
1551.10.33 by Aaron Bentley
Updates from review
624
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
625
        return self._find_revision_info(branch, self.spec)
626
627
    @staticmethod
628
    def _find_revision_info(branch, other_location):
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
629
        from bzrlib.branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
630
1551.10.33 by Aaron Bentley
Updates from review
631
        other_branch = Branch.open(other_location)
1390 by Robert Collins
pair programming worx... merge integration and weave
632
        revision_a = branch.last_revision()
633
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
634
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
635
            if r in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
636
                raise errors.NoCommits(b)
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
637
        revision_source = revision.MultipleRevisionSources(
638
                branch.repository, other_branch.repository)
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
639
        graph = branch.repository.get_graph(other_branch.repository)
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
640
        revision_a = revision.ensure_null(revision_a)
641
        revision_b = revision.ensure_null(revision_b)
642
        if revision.NULL_REVISION in (revision_a, revision_b):
643
            rev_id = revision.NULL_REVISION
644
        else:
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
645
            rev_id = graph.find_unique_lca(revision_a, revision_b)
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
646
            if rev_id == revision.NULL_REVISION:
647
                raise errors.NoCommonAncestor(revision_a, revision_b)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
648
        try:
649
            revno = branch.revision_id_to_revno(rev_id)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
650
        except errors.NoSuchRevision:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
651
            revno = None
652
        return RevisionInfo(branch, revno, rev_id)
1551.10.33 by Aaron Bentley
Updates from review
653
654
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
655
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
656
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
657
1432 by Robert Collins
branch: namespace
658
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
659
    """Selects the last revision of a specified branch."""
660
661
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
662
663
    Supply the path to a branch to select its last revision.
664
665
    examples:
666
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
667
    """
668
    prefix = 'branch:'
669
670
    def _match_on(self, branch, revs):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
671
        from bzrlib.branch import Branch
672
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
673
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
674
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
675
            raise errors.NoCommits(other_branch)
1432 by Robert Collins
branch: namespace
676
        # 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.
677
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
678
        try:
679
            revno = branch.revision_id_to_revno(revision_b)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
680
        except errors.NoSuchRevision:
1432 by Robert Collins
branch: namespace
681
            revno = None
682
        return RevisionInfo(branch, revno, revision_b)
683
        
684
SPEC_TYPES.append(RevisionSpec_branch)
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
685
686
1551.10.33 by Aaron Bentley
Updates from review
687
class RevisionSpec_submit(RevisionSpec_ancestor):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
688
    """Selects a common ancestor with a submit branch."""
689
690
    help_txt = """Selects a common ancestor with the submit branch.
691
692
    Diffing against this shows all the changes that were made in this branch,
693
    and is a good predictor of what merge will do.  The submit branch is
694
    used by the bundle and merge directive comands.  If no submit branch
695
    is specified, the parent branch is used instead.
696
697
    The common ancestor is the last revision that existed in both
698
    branches. Usually this is the branch point, but it could also be
699
    a revision that was merged.
700
701
    examples:
702
      $ bzr diff -r submit:
703
    """
1551.10.33 by Aaron Bentley
Updates from review
704
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
705
    prefix = 'submit:'
706
707
    def _match_on(self, branch, revs):
708
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
709
        submit_location = branch.get_submit_branch()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
710
        location_type = 'submit branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
711
        if submit_location is None:
712
            submit_location = branch.get_parent()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
713
            location_type = 'parent branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
714
        if submit_location is None:
715
            raise errors.NoSubmitBranch(branch)
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
716
        trace.note('Using %s %s', location_type, submit_location)
1551.10.33 by Aaron Bentley
Updates from review
717
        return self._find_revision_info(branch, submit_location)
718
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
719
1551.10.33 by Aaron Bentley
Updates from review
720
SPEC_TYPES.append(RevisionSpec_submit)