~bzr-pqm/bzr/bzr.dev

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