/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
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
#
369 by Martin Pool
- Split out log printing into new show_log function
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
#
369 by Martin Pool
- Split out log printing into new show_log function
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
#
369 by Martin Pool
- Split out log printing into new show_log function
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
375 by Martin Pool
- New command touching-revisions and function to trace
17
18
527 by Martin Pool
- refactor log command
19
"""Code to show logs of changes.
20
21
Various flavors of log can be produced:
22
23
* for one file, or the whole tree, and (not done yet) for
24
  files in a given directory
25
26
* in "verbose" mode with a description of what changed from one
27
  version to the next
28
29
* with file-ids and revision-ids shown
30
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
31
Logs are actually written out through an abstract LogFormatter
32
interface, which allows for different preferred formats.  Plugins can
33
register formats too.
34
35
Logs can be produced in either forward (oldest->newest) or reverse
36
(newest->oldest) order.
37
38
Logs can be filtered to show only revisions matching a particular
39
search string, or within a particular range of revisions.  The range
40
can be given as date/times, which are reduced to revisions before
41
calling in here.
42
43
In verbose mode we show a summary of what changed in each particular
44
revision.  Note that this is the delta for changes in that revision
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
45
relative to its left-most parent, not the delta relative to the last
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
46
logged revision.  So for example if you ask for a verbose log of
47
changes touching hello.c you will get a list of those revisions also
48
listing other things that were changed in the same revision, but not
49
all the changes since the previous revision that touched hello.c.
527 by Martin Pool
- refactor log command
50
"""
51
2997.1.2 by Kent Gibson
Move all imports to top of log.py
52
import codecs
53
from itertools import (
54
    izip,
55
    )
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
56
import re
2997.1.2 by Kent Gibson
Move all imports to top of log.py
57
import sys
58
from warnings import (
59
    warn,
60
    )
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
61
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
62
from bzrlib.lazy_import import lazy_import
63
lazy_import(globals(), """
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
64
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
65
from bzrlib import (
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
66
    config,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
67
    errors,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
68
    repository as _mod_repository,
69
    revision as _mod_revision,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
70
    revisionspec,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
71
    trace,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
72
    tsort,
73
    )
74
""")
75
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
76
from bzrlib import (
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
77
    registry,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
78
    )
79
from bzrlib.osutils import (
80
    format_date,
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
81
    get_terminal_encoding,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
82
    terminal_width,
83
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
84
375 by Martin Pool
- New command touching-revisions and function to trace
85
86
def find_touching_revisions(branch, file_id):
87
    """Yield a description of revisions which affect the file_id.
88
89
    Each returned element is (revno, revision_id, description)
90
91
    This is the list of revisions where the file is either added,
92
    modified, renamed or deleted.
93
94
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
95
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
96
    """
97
    last_ie = None
98
    last_path = None
99
    revno = 1
100
    for revision_id in branch.revision_history():
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
101
        this_inv = branch.repository.get_revision_inventory(revision_id)
375 by Martin Pool
- New command touching-revisions and function to trace
102
        if file_id in this_inv:
103
            this_ie = this_inv[file_id]
104
            this_path = this_inv.id2path(file_id)
105
        else:
106
            this_ie = this_path = None
107
108
        # now we know how it was last time, and how it is in this revision.
109
        # are those two states effectively the same or not?
110
111
        if not this_ie and not last_ie:
112
            # not present in either
113
            pass
114
        elif this_ie and not last_ie:
115
            yield revno, revision_id, "added " + this_path
116
        elif not this_ie and last_ie:
117
            # deleted here
118
            yield revno, revision_id, "deleted " + last_path
119
        elif this_path != last_path:
120
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
121
        elif (this_ie.text_size != last_ie.text_size
122
              or this_ie.text_sha1 != last_ie.text_sha1):
123
            yield revno, revision_id, "modified " + this_path
124
125
        last_ie = this_ie
126
        last_path = this_path
127
        revno += 1
128
129
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
130
def _enumerate_history(branch):
131
    rh = []
132
    revno = 1
133
    for rev_id in branch.revision_history():
134
        rh.append((revno, rev_id))
135
        revno += 1
136
    return rh
137
138
378 by Martin Pool
- New usage bzr log FILENAME
139
def show_log(branch,
794 by Martin Pool
- Merge John's nice short-log format.
140
             lf,
527 by Martin Pool
- refactor log command
141
             specific_fileid=None,
378 by Martin Pool
- New usage bzr log FILENAME
142
             verbose=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
143
             direction='reverse',
144
             start_revision=None,
900 by Martin Pool
- patch from john to search for matching commits
145
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
146
             search=None,
3936.3.8 by Ian Clatworthy
back-out --strict
147
             limit=None):
369 by Martin Pool
- Split out log printing into new show_log function
148
    """Write out human-readable log of commits to this branch.
149
3874.2.2 by Vincent Ladeuil
Cleanup show_log doc string.
150
    :param lf: The LogFormatter object showing the output.
151
152
    :param specific_fileid: If not None, list only the commits affecting the
153
        specified file, rather than all commits.
154
155
    :param verbose: If True show added/changed/deleted/renamed files.
156
157
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
158
        earliest to latest.
159
160
    :param start_revision: If not None, only show revisions >= start_revision
161
162
    :param end_revision: If not None, only show revisions <= end_revision
163
164
    :param search: If not None, only show revisions with matching commit
165
        messages
166
167
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
168
        if None or 0.
369 by Martin Pool
- Split out log printing into new show_log function
169
    """
1417.1.7 by Robert Collins
teach log it needs a read lock
170
    branch.lock_read()
171
    try:
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
172
        if getattr(lf, 'begin_log', None):
173
            lf.begin_log()
174
1756.1.6 by Aaron Bentley
Revert locking fix
175
        _show_log(branch, lf, specific_fileid, verbose, direction,
3936.3.8 by Ian Clatworthy
back-out --strict
176
                  start_revision, end_revision, search, limit)
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
177
178
        if getattr(lf, 'end_log', None):
179
            lf.end_log()
1417.1.7 by Robert Collins
teach log it needs a read lock
180
    finally:
181
        branch.unlock()
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
182
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
183
1417.1.7 by Robert Collins
teach log it needs a read lock
184
def _show_log(branch,
185
             lf,
186
             specific_fileid=None,
187
             verbose=False,
188
             direction='reverse',
189
             start_revision=None,
190
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
191
             search=None,
3936.3.8 by Ian Clatworthy
back-out --strict
192
             limit=None):
1417.1.7 by Robert Collins
teach log it needs a read lock
193
    """Worker function for show_log - see show_log."""
794 by Martin Pool
- Merge John's nice short-log format.
194
    if not isinstance(lf, LogFormatter):
195
        warn("not a LogFormatter instance: %r" % lf)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
196
    if specific_fileid:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
197
        trace.mutter('get log for file_id %r', specific_fileid)
3936.3.1 by Ian Clatworthy
refactor _show_log
198
199
    # Consult the LogFormatter about what it needs and can handle
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
200
    generate_merge_revisions = getattr(lf, 'supports_merge_revisions', False)
201
    allow_single_merge_revision = getattr(lf,
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
202
        'supports_single_merge_revision', generate_merge_revisions)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
203
    generate_tags = getattr(lf, 'supports_tags', False)
3936.3.1 by Ian Clatworthy
refactor _show_log
204
    if generate_tags and branch.supports_tags():
205
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
206
    else:
207
        rev_tag_dict = {}
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
208
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
209
3936.3.1 by Ian Clatworthy
refactor _show_log
210
    # Find and print the interesting revisions
3936.3.13 by Ian Clatworthy
feedback from jameinel
211
    log_count = 0
212
    revision_iterator = _create_log_revision_iterator(branch,
213
        start_revision, end_revision, direction, specific_fileid, search,
214
        generate_merge_revisions, allow_single_merge_revision,
3936.3.22 by Ian Clatworthy
make incremental file logging fast again
215
        generate_delta)
3936.3.13 by Ian Clatworthy
feedback from jameinel
216
    for revs in revision_iterator:
217
        for (rev_id, revno, merge_depth), rev, delta in revs:
218
            lr = LogRevision(rev, revno, merge_depth, delta,
219
                             rev_tag_dict.get(rev_id))
220
            lf.log_revision(lr)
221
            if limit:
222
                log_count += 1
223
                if log_count >= limit:
224
                    return
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
225
226
3936.3.1 by Ian Clatworthy
refactor _show_log
227
def _create_log_revision_iterator(branch, start_revision, end_revision,
228
    direction, specific_fileid, search, generate_merge_revisions,
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
229
    allow_single_merge_revision, generate_delta,
3936.3.22 by Ian Clatworthy
make incremental file logging fast again
230
    force_incremental_matching=False):
3936.3.1 by Ian Clatworthy
refactor _show_log
231
    """Create a revision iterator for log.
232
233
    :param branch: The branch being logged.
234
    :param start_revision: If not None, only show revisions >= start_revision
235
    :param end_revision: If not None, only show revisions <= end_revision
236
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
237
        earliest to latest.
238
    :param specific_fileid: If not None, list only the commits affecting the
239
        specified file.
240
    :param search: If not None, only show revisions with matching commit
241
        messages.
242
    :param generate_merge_revisions: If False, show only mainline revisions.
3936.3.2 by Ian Clatworthy
minor cleanups
243
    :param allow_single_merge_revision: If True, logging of a single
244
        revision off the mainline is to be allowed
3936.3.1 by Ian Clatworthy
refactor _show_log
245
    :param generate_delta: Whether to generate a delta for each revision.
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
246
    :param force_incremental_matching: if there's a file_id, use deltas
247
        to match it unconditionally
3936.3.1 by Ian Clatworthy
refactor _show_log
248
249
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
250
        delta).
251
    """
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
252
    rev_limits = _get_revision_limits(branch, start_revision, end_revision)
253
    _, _, _, start_rev_id, _, end_rev_id = rev_limits
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
254
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
3936.3.17 by Ian Clatworthy
delta filtering bug fix
255
    # Delta filtering allows revisions to be displayed incrementally
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
256
    # though the total time is much slower for huge repositories: log -v
257
    # is the *lower* performance bound. At least until the split
258
    # inventory format arrives, per-file-graph needs to remain the
259
    # default when no limits are given. Delta filtering should give more
260
    # accurate results (e.g. inclusion of FILE deletions) so arguably
261
    # it should always be used in the future.
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
262
    use_deltas_for_matching = specific_fileid and (force_incremental_matching
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
263
        or generate_delta or start_rev_id or end_rev_id)
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
264
    if use_deltas_for_matching:
265
        view_revisions = _calc_view_revisions(branch, rev_limits,
266
            direction, generate_merge_revisions, allow_single_merge_revision)
267
        def only_the_file(path, file_id):
268
            return file_id == specific_fileid
3936.3.17 by Ian Clatworthy
delta filtering bug fix
269
        return make_log_rev_iterator(branch, view_revisions, generate_delta,
270
            search, delta_entry_filter=only_the_file)
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
271
    else:
272
        view_revisions = _calc_view_revisions(branch, rev_limits,
273
            direction, generate_merge_revisions or specific_fileid,
274
            allow_single_merge_revision)
275
        if specific_fileid:
276
            view_revisions = _filter_revisions_touching_file_id(branch,
277
                specific_fileid, view_revisions,
278
                include_merges=generate_merge_revisions)
279
        return make_log_rev_iterator(branch, view_revisions, generate_delta,
280
            search)
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
281
282
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
283
class _StartNotLinearAncestor(Exception):
284
    """Raised when a start revision is not found walking left-hand history."""
285
286
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
287
def _calc_view_revisions(branch, rev_limits, direction,
3936.3.8 by Ian Clatworthy
back-out --strict
288
        generate_merge_revisions, allow_single_merge_revision):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
289
    """Calculate the revisions to view.
290
291
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
292
             a list of the same tuples.
293
    """
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
294
    br_revno, br_rev_id, start_revno, start_rev_id, end_revno, end_rev_id = \
295
        rev_limits
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
296
    if br_revno == 0:
297
        return []
298
3936.3.10 by Ian Clatworthy
more single revision clean-up
299
    # If a single revision is requested, check we can handle it
300
    generate_single_revision = (start_rev_id and start_rev_id == end_rev_id)
301
    if generate_single_revision:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
302
        if start_rev_id == br_rev_id:
303
            # It's the tip
304
            if (not generate_merge_revisions or
305
                not _has_merges(branch, br_rev_id)):
306
                return [(br_rev_id, br_revno, 0)]
307
            else:
308
                # We need the merge revisions as well
309
                generate_single_revision = False
310
        elif (not generate_merge_revisions or
311
            not _has_merges(branch, start_rev_id)):
3936.3.26 by Ian Clatworthy
use new dotted-revno-revision-id conversion methods to simplify & speed up code
312
            revno = branch.revision_id_to_dotted_revno(start_rev_id)
313
            if len(revno) > 1 and not allow_single_merge_revision:
314
                # It's a merge revision and the log formatter is
315
                # completely brain dead. This "feature" of allowing
316
                # log formatters incapable of displaying dotted revnos
317
                # ought to be deprecated IMNSHO. IGC 20091022
318
                raise errors.BzrCommandError('Selected log formatter only'
319
                    ' supports mainline revisions.')
320
            revno_str = '.'.join(str(n) for n in revno)
321
            return [(start_rev_id, revno_str, 0)]
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
322
        else:
323
            generate_single_revision = False
3936.3.10 by Ian Clatworthy
more single revision clean-up
324
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
325
    # If we only want to see linear revisions, we can iterate ...
3936.3.10 by Ian Clatworthy
more single revision clean-up
326
    if not generate_merge_revisions:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
327
        result = _linear_view_revisions(branch, rev_limits)
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
328
        # If a start limit was given and it's not obviously an
329
        # ancestor of the end limit, check it before outputting anything
330
        if start_rev_id and not (_on_mainline(branch, start_rev_id) and
331
            _on_mainline(branch, end_rev_id)):
3936.3.13 by Ian Clatworthy
feedback from jameinel
332
            try:
333
                result = list(result)
334
            except _StartNotLinearAncestor:
335
                raise errors.BzrCommandError('Start revision not found in'
336
                    ' left-hand history of end revision.')
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
337
        if direction == 'forward':
338
            result = reversed(list(result))
339
        return result
340
3936.3.15 by Ian Clatworthy
faster long log for a limited range with no merges
341
    # If we're only looking at a limited linear range, we can skip
342
    # generating merge revisions if there aren't any merges
343
    if start_rev_id:
344
        result = []
345
        try:
346
            for rev_id, revno, depth in \
347
                _linear_view_revisions(branch, rev_limits):
348
                if _has_merges(branch, rev_id):
349
                    break
350
                result.append((rev_id, revno, depth))
351
            else:
352
                # Success!
353
                if direction == 'forward':
354
                    result = reversed(result)
355
                return result
356
        except _StartNotLinearAncestor:
357
            # Abort - we need the smart filtering below
358
            pass
359
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
360
    # Otherwise, the algorithm is O(history) for now ...
361
3936.3.10 by Ian Clatworthy
more single revision clean-up
362
    # Do the filtering
3936.3.4 by Ian Clatworthy
fix empty_branch log
363
    mainline_revs, rev_nos = _get_mainline_revs(branch, rev_limits)
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
364
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
365
                          direction, include_merges=generate_merge_revisions)
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
366
    if direction == 'reverse':
367
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
368
    view_revisions = _filter_revision_range(list(view_revs_iter),
369
                                            start_rev_id,
370
                                            end_rev_id)
3936.3.28 by Ian Clatworthy
api compatibility: calculate_view_revisions rebases merge depth again
371
    return _rebase_merge_depth(view_revisions)
372
373
374
def _rebase_merge_depth(view_revisions):
375
    """Adjust depths upwards so the top level is 0."""
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
376
    # Rebase merge_depth - unless there are no revisions or 
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
377
    # either the first or last revision have merge_depth = 0.
378
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
2466.12.3 by Kent Gibson
Fix JAM's review comments for left align patch
379
        min_depth = min([d for r,n,d in view_revisions])
380
        if min_depth != 0:
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
381
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
382
    return view_revisions
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
383
530 by Martin Pool
- put back verbose log support for reversed logs
384
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
385
def _has_merges(branch, rev_id):
386
    """Does a revision have multiple parents or not?"""
387
    return len(branch.repository.get_revision(rev_id).parent_ids) > 1
388
389
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
390
def _on_mainline(branch, rev_id):
391
    """Is rev_id on the mainline of a branch?"""
392
    if rev_id:
393
        try:
394
            branch.revision_id_to_revno(rev_id)
395
        except errors.NoSuchRevision:
396
            return False
397
    return True
398
399
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
400
def _linear_view_revisions(branch, revision_limits):
401
    """Calculate a sequence of revisions to view, newest to oldest.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
402
403
    :param revision_limits: a tuple as returned by _get_revision_limits()
404
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
405
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
406
      is not found walking the left-hand history
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
407
    """
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
408
    br_revno, br_rev_id, start_revno, start_rev_id, end_revno, end_rev_id = \
409
        revision_limits
3943.4.5 by John Arbash Meinel
Restore _linear_view_revisions.
410
    repo = branch.repository
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
411
    if start_rev_id is None and end_rev_id is None:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
412
        cur_revno = br_revno
413
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
414
            yield revision_id, str(cur_revno), 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
415
            cur_revno -= 1
3936.3.14 by Ian Clatworthy
bug fix
416
    else:
417
        if end_rev_id is None:
418
            end_rev_id = br_rev_id
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
419
        found_start = start_rev_id is None
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
420
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
3936.3.26 by Ian Clatworthy
use new dotted-revno-revision-id conversion methods to simplify & speed up code
421
            revno = branch.revision_id_to_dotted_revno(revision_id)
422
            revno_str = '.'.join(str(n) for n in revno)
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
423
            if not found_start and revision_id == start_rev_id:
424
                yield revision_id, revno_str, 0
425
                found_start = True
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
426
                break
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
427
            else:
428
                yield revision_id, revno_str, 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
429
        else:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
430
            if not found_start:
431
                raise _StartNotLinearAncestor()
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
432
433
3936.3.13 by Ian Clatworthy
feedback from jameinel
434
def calculate_view_revisions(branch, start_revision, end_revision, direction,
435
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
436
    """Calculate the revisions to view.
437
438
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
439
             a list of the same tuples.
440
    """
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
441
    # This method is no longer called by the main code path.
442
    # It is retained for API compatibility and may be deprecated
443
    # soon. IGC 20090116
444
    rev_limits = _get_revision_limits(branch, start_revision, end_revision)
445
    view_revisions = _calc_view_revisions(branch, rev_limits,
3936.3.13 by Ian Clatworthy
feedback from jameinel
446
        direction, generate_merge_revisions or specific_fileid,
447
        allow_single_merge_revision)
448
    if specific_fileid:
449
        view_revisions = _filter_revisions_touching_file_id(branch,
450
            specific_fileid, view_revisions,
451
            include_merges=generate_merge_revisions)
3936.3.28 by Ian Clatworthy
api compatibility: calculate_view_revisions rebases merge depth again
452
    return _rebase_merge_depth(view_revisions)
3936.3.13 by Ian Clatworthy
feedback from jameinel
453
454
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
455
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
456
        delta_entry_filter=None):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
457
    """Create a revision iterator for log.
458
459
    :param branch: The branch being logged.
460
    :param view_revisions: The revisions being viewed.
461
    :param generate_delta: Whether to generate a delta for each revision.
462
    :param search: A user text search string.
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
463
    :param delta_entry_filter: If set, a delta is always generated and
464
      one of its entries must pass this filter for a revision to be kept.
465
      The generated delta is only retained if generate_delta is True.
3642.1.7 by Robert Collins
Review feedback.
466
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
467
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
468
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
469
    # Convert view_revisions into (view, None, None) groups to fit with
470
    # the standard interface here.
471
    if type(view_revisions) == list:
3642.1.7 by Robert Collins
Review feedback.
472
        # A single batch conversion is faster than many incremental ones.
473
        # As we have all the data, do a batch conversion.
3642.1.5 by Robert Collins
Separate out batching of revisions.
474
        nones = [None] * len(view_revisions)
475
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
476
    else:
477
        def _convert():
478
            for view in view_revisions:
479
                yield (view, None, None)
480
        log_rev_iterator = iter([_convert()])
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
481
    for adapter in log_adapters:
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
482
        log_rev_iterator = adapter(branch, generate_delta or
483
            delta_entry_filter, search, log_rev_iterator)
484
    if delta_entry_filter:
485
        log_rev_iterator = _filter_delta_items(log_rev_iterator,
486
            delta_entry_filter, generate_delta)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
487
    return log_rev_iterator
488
489
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
490
def _filter_delta_items(log_rev_iterator, filter, retain_delta):
491
    for revs in log_rev_iterator:
492
        new_revs = []
493
        for (rev_id, revno, merge_depth), rev, delta in revs:
494
            if _delta_matches_filter(delta, filter):
495
                if not retain_delta:
496
                    delta = None
497
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
498
        yield new_revs
499
500
501
def _delta_matches_filter(delta, filter):
502
    """Check is a delta matches a filter."""
503
    for l in (delta.modified, delta.added, delta.removed, delta.kind_changed):
504
        for item in l:
505
            if filter(item[0], item[1]):
506
                return True
507
    for item in delta.renamed:
508
        if filter(item[0], item[2]) or filter(item[1], item[2]):
509
            return True
510
    return False
511
512
3642.1.7 by Robert Collins
Review feedback.
513
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
514
    """Create a filtered iterator of log_rev_iterator matching on a regex.
515
516
    :param branch: The branch being logged.
517
    :param generate_delta: Whether to generate a delta for each revision.
518
    :param search: A user text search string.
519
    :param log_rev_iterator: An input iterator containing all revisions that
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
520
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
521
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
522
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
523
    """
524
    if search is None:
525
        return log_rev_iterator
526
    # Compile the search now to get early errors.
527
    searchRE = re.compile(search, re.IGNORECASE)
528
    return _filter_message_re(searchRE, log_rev_iterator)
529
530
531
def _filter_message_re(searchRE, log_rev_iterator):
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
532
    for revs in log_rev_iterator:
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
533
        new_revs = []
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
534
        for (rev_id, revno, merge_depth), rev, delta in revs:
535
            if searchRE.search(rev.message):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
536
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
537
        yield new_revs
538
539
3642.1.7 by Robert Collins
Review feedback.
540
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
541
    """Add revision deltas to a log iterator if needed.
542
543
    :param branch: The branch being logged.
544
    :param generate_delta: Whether to generate a delta for each revision.
545
    :param search: A user text search string.
546
    :param log_rev_iterator: An input iterator containing all revisions that
547
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
548
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
549
        delta).
550
    """
551
    if not generate_delta:
552
        return log_rev_iterator
553
    return _generate_deltas(branch.repository, log_rev_iterator)
554
555
556
def _generate_deltas(repository, log_rev_iterator):
3642.1.7 by Robert Collins
Review feedback.
557
    """Create deltas for each batch of revisions in log_rev_iterator."""
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
558
    for revs in log_rev_iterator:
559
        revisions = [rev[1] for rev in revs]
560
        deltas = repository.get_deltas_for_revisions(revisions)
561
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
562
        yield revs
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
563
564
3642.1.7 by Robert Collins
Review feedback.
565
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
566
    """Extract revision objects from the repository
567
568
    :param branch: The branch being logged.
569
    :param generate_delta: Whether to generate a delta for each revision.
570
    :param search: A user text search string.
571
    :param log_rev_iterator: An input iterator containing all revisions that
572
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
573
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
574
        delta).
575
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
576
    repository = branch.repository
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
577
    for revs in log_rev_iterator:
578
        # r = revision_id, n = revno, d = merge depth
579
        revision_ids = [view[0] for view, _, _ in revs]
580
        revisions = repository.get_revisions(revision_ids)
581
        revs = [(rev[0], revision, rev[2]) for rev, revision in
582
            izip(revs, revisions)]
583
        yield revs
584
585
3642.1.7 by Robert Collins
Review feedback.
586
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.5 by Robert Collins
Separate out batching of revisions.
587
    """Group up a single large batch into smaller ones.
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
588
589
    :param branch: The branch being logged.
590
    :param generate_delta: Whether to generate a delta for each revision.
591
    :param search: A user text search string.
3642.1.5 by Robert Collins
Separate out batching of revisions.
592
    :param log_rev_iterator: An input iterator containing all revisions that
593
        could be displayed, in lists.
3874.2.4 by Vincent Ladeuil
Fix too long lines.
594
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
595
        delta).
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
596
    """
597
    repository = branch.repository
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
598
    num = 9
3642.1.5 by Robert Collins
Separate out batching of revisions.
599
    for batch in log_rev_iterator:
600
        batch = iter(batch)
601
        while True:
602
            step = [detail for _, detail in zip(range(num), batch)]
603
            if len(step) == 0:
604
                break
605
            yield step
606
            num = min(int(num * 1.5), 200)
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
607
608
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
609
def _get_revision_limits(branch, start_revision, end_revision):
610
    """Get and check revision limits.
611
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
612
    :param  branch: The branch containing the revisions. 
613
614
    :param  start_revision: The first revision to be logged.
615
            For backwards compatibility this may be a mainline integer revno,
616
            but for merge revision support a RevisionInfo is expected.
617
618
    :param  end_revision: The last revision to be logged.
619
            For backwards compatibility this may be a mainline integer revno,
620
            but for merge revision support a RevisionInfo is expected.
621
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
622
    :return: (br_revno, br_rev_id, start_revno, start_rev_id, end_revno,
623
        end_rev_id) tuple.
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
624
    """
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
625
    branch_revno, branch_rev_id = branch.last_revision_info()
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
626
    start_rev_id = None
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
627
    if start_revision is None:
628
        start_revno = 1
629
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
630
        if isinstance(start_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
631
            start_rev_id = start_revision.rev_id
632
            start_revno = start_revision.revno or 1
633
        else:
634
            branch.check_real_revno(start_revision)
635
            start_revno = start_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
636
            start_rev_id = branch.get_rev_id(start_revno)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
637
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
638
    end_rev_id = None
639
    if end_revision is None:
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
640
        end_revno = branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
641
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
642
        if isinstance(end_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
643
            end_rev_id = end_revision.rev_id
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
644
            end_revno = end_revision.revno or branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
645
        else:
646
            branch.check_real_revno(end_revision)
647
            end_revno = end_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
648
            end_rev_id = branch.get_rev_id(end_revno)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
649
3936.3.4 by Ian Clatworthy
fix empty_branch log
650
    if branch_revno != 0:
651
        if (start_rev_id == _mod_revision.NULL_REVISION
652
            or end_rev_id == _mod_revision.NULL_REVISION):
653
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
654
        if start_revno > end_revno:
655
            raise errors.BzrCommandError("Start revision must be older than "
656
                                         "the end revision.")
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
657
    return (branch_revno, branch_rev_id, start_revno, start_rev_id, end_revno,
658
        end_rev_id)
659
660
3936.3.4 by Ian Clatworthy
fix empty_branch log
661
def _get_mainline_revs(branch, revision_limits):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
662
    """Get the mainline revisions from the branch.
663
    
664
    Generates the list of mainline revisions for the branch. Also map the
665
    revisions to rev_ids, to be used in the later filtering stage.
666
    
667
    :param  branch: The branch containing the revisions. 
3936.3.4 by Ian Clatworthy
fix empty_branch log
668
    :param revision_limits: a tuple as returned by _get_revision_limits()
669
670
    :return: A (mainline_revs, rev_nos) tuple.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
671
    """
672
    (br_revno, br_rev_id, start_revno, start_rev_id, end_revno, end_rev_id) = \
3936.3.4 by Ian Clatworthy
fix empty_branch log
673
        revision_limits
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
674
    cur_revno = br_revno
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
675
    rev_nos = {}
676
    mainline_revs = []
677
    for revision_id in branch.repository.iter_reverse_revision_history(
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
678
                        br_rev_id):
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
679
        if cur_revno < start_revno:
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
680
            # We have gone far enough, but we always add 1 more revision
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
681
            rev_nos[revision_id] = cur_revno
682
            mainline_revs.append(revision_id)
683
            break
684
        if cur_revno <= end_revno:
685
            rev_nos[revision_id] = cur_revno
686
            mainline_revs.append(revision_id)
687
        cur_revno -= 1
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
688
    else:
689
        # We walked off the edge of all revisions, so we add a 'None' marker
690
        mainline_revs.append(None)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
691
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
692
    mainline_revs.reverse()
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
693
694
    # override the mainline to look like the revision history.
3936.3.4 by Ian Clatworthy
fix empty_branch log
695
    return mainline_revs, rev_nos
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
696
697
698
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
699
    """Filter view_revisions based on revision ranges.
700
701
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
702
            tuples to be filtered.
703
704
    :param start_rev_id: If not NONE specifies the first revision to be logged.
705
            If NONE then all revisions up to the end_rev_id are logged.
706
707
    :param end_rev_id: If not NONE specifies the last revision to be logged.
708
            If NONE then all revisions up to the end of the log are logged.
709
710
    :return: The filtered view_revisions.
711
    """
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
712
    if start_rev_id or end_rev_id:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
713
        revision_ids = [r for r, n, d in view_revisions]
714
        if start_rev_id:
715
            start_index = revision_ids.index(start_rev_id)
716
        else:
717
            start_index = 0
718
        if start_rev_id == end_rev_id:
719
            end_index = start_index
720
        else:
721
            if end_rev_id:
722
                end_index = revision_ids.index(end_rev_id)
723
            else:
724
                end_index = len(view_revisions) - 1
725
        # To include the revisions merged into the last revision, 
726
        # extend end_rev_id down to, but not including, the next rev
727
        # with the same or lesser merge_depth
728
        end_merge_depth = view_revisions[end_index][2]
729
        try:
730
            for index in xrange(end_index+1, len(view_revisions)+1):
731
                if view_revisions[index][2] <= end_merge_depth:
732
                    end_index = index - 1
733
                    break
734
        except IndexError:
735
            # if the search falls off the end then log to the end as well
736
            end_index = len(view_revisions) - 1
737
        view_revisions = view_revisions[start_index:end_index+1]
738
    return view_revisions
739
740
3940.1.3 by Ian Clatworthy
fix code
741
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
742
    include_merges=True):
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
743
    r"""Return the list of revision ids which touch a given file id.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
744
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
745
    The function filters view_revisions and returns a subset.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
746
    This includes the revisions which directly change the file id,
747
    and the revisions which merge these changes. So if the
748
    revision graph is::
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
749
        A-.
750
        |\ \
751
        B C E
752
        |/ /
753
        D |
754
        |\|
755
        | F
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
756
        |/
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
757
        G
758
759
    And 'C' changes a file, then both C and D will be returned. F will not be
760
    returned even though it brings the changes to C into the branch starting
761
    with E. (Note that if we were using F as the tip instead of G, then we
762
    would see C, D, F.)
763
764
    This will also be restricted based on a subset of the mainline.
765
766
    :param branch: The branch where we can get text revision information.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
767
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
768
    :param file_id: Filter out revisions that do not touch file_id.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
769
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
770
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
771
        tuples. This is the list of revisions which will be filtered. It is
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
772
        assumed that view_revisions is in merge_sort order (i.e. newest
773
        revision first ).
774
3940.1.3 by Ian Clatworthy
fix code
775
    :param include_merges: include merge revisions in the result or not
776
2359.1.8 by John Arbash Meinel
doc
777
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
778
    """
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
779
    # Lookup all possible text keys to determine which ones actually modified
780
    # the file.
781
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
3711.3.16 by John Arbash Meinel
Doc update.
782
    # Looking up keys in batches of 1000 can cut the time in half, as well as
783
    # memory consumption. GraphIndex *does* like to look for a few keys in
784
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
3711.3.19 by John Arbash Meinel
Add a TODO discussing how our index requests should evolve.
785
    # TODO: This code needs to be re-evaluated periodically as we tune the
786
    #       indexing layer. We might consider passing in hints as to the known
787
    #       access pattern (sparse/clustered, high success rate/low success
788
    #       rate). This particular access is clustered with a low success rate.
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
789
    get_parent_map = branch.repository.texts.get_parent_map
790
    modified_text_revisions = set()
791
    chunk_size = 1000
792
    for start in xrange(0, len(text_keys), chunk_size):
793
        next_keys = text_keys[start:start + chunk_size]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
794
        # Only keep the revision_id portion of the key
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
795
        modified_text_revisions.update(
796
            [k[1] for k in get_parent_map(next_keys)])
797
    del text_keys, next_keys
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
798
799
    result = []
800
    # Track what revisions will merge the current revision, replace entries
801
    # with 'None' when they have been added to result
802
    current_merge_stack = [None]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
803
    for info in view_revisions:
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
804
        rev_id, revno, depth = info
805
        if depth == len(current_merge_stack):
806
            current_merge_stack.append(info)
807
        else:
808
            del current_merge_stack[depth + 1:]
809
            current_merge_stack[-1] = info
810
811
        if rev_id in modified_text_revisions:
812
            # This needs to be logged, along with the extra revisions
813
            for idx in xrange(len(current_merge_stack)):
814
                node = current_merge_stack[idx]
815
                if node is not None:
3940.1.3 by Ian Clatworthy
fix code
816
                    if include_merges or node[2] == 0:
817
                        result.append(node)
818
                        current_merge_stack[idx] = None
3711.3.4 by John Arbash Meinel
Significantly faster, but consuming more memory.
819
    return result
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
820
821
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
822
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
823
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
824
    """Produce an iterator of revisions to show
825
    :return: an iterator of (revision_id, revno, merge_depth)
826
    (if there is no revno for a revision, None is supplied)
827
    """
3943.1.1 by Ian Clatworthy
apply jam's log --short fix (Ian Clatworthy)
828
    if not include_merges:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
829
        revision_ids = mainline_revs[1:]
830
        if direction == 'reverse':
831
            revision_ids.reverse()
832
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
833
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
834
        return
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
835
    graph = branch.repository.get_graph()
836
    # This asks for all mainline revisions, which means we only have to spider
837
    # sideways, rather than depth history. That said, its still size-of-history
838
    # and should be addressed.
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
839
    # mainline_revisions always includes an extra revision at the beginning, so
840
    # don't request it.
3287.6.8 by Robert Collins
Reduce code duplication as per review.
841
    parent_map = dict(((key, value) for key, value in
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
842
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
843
    # filter out ghosts; merge_sort errors on ghosts.
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
844
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
845
    merge_sorted_revisions = tsort.merge_sort(
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
846
        rev_graph,
1756.2.18 by Aaron Bentley
Factor out the revision list generation
847
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
848
        mainline_revs,
849
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
850
851
    if direction == 'forward':
852
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
853
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
854
    elif direction != 'reverse':
855
        raise ValueError('invalid direction %r' % direction)
856
3874.2.4 by Vincent Ladeuil
Fix too long lines.
857
    for (sequence, rev_id, merge_depth, revno, end_of_merge
858
         ) in merge_sorted_revisions:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
859
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
860
861
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
862
def reverse_by_depth(merge_sorted_revisions, _depth=0):
863
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
864
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
865
    Revisions with a different depth are sorted as a group with the previous
866
    revision of that depth.  There may be no topological justification for this,
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
867
    but it looks much nicer.
868
    """
3842.2.6 by Vincent Ladeuil
Fix typo.
869
    # Add a fake revision at start so that we can always attach sub revisions
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
870
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
871
    zd_revisions = []
872
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
873
        if val[2] == _depth:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
874
            # Each revision at the current depth becomes a chunk grouping all
875
            # higher depth revisions.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
876
            zd_revisions.append([val])
877
        else:
878
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
879
    for revisions in zd_revisions:
880
        if len(revisions) > 1:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
881
            # We have higher depth revisions, let reverse them locally
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
882
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
883
    zd_revisions.reverse()
884
    result = []
885
    for chunk in zd_revisions:
886
        result.extend(chunk)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
887
    if _depth == 0:
888
        # Top level call, get rid of the fake revisions that have been added
889
        result = [r for r in result if r[0] is not None and r[1] is not None]
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
890
    return result
891
892
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
893
class LogRevision(object):
894
    """A revision to be logged (by LogFormatter.log_revision).
895
896
    A simple wrapper for the attributes of a revision to be logged.
897
    The attributes may or may not be populated, as determined by the 
898
    logging options and the log formatter capabilities.
899
    """
900
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
901
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
902
                 tags=None):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
903
        self.rev = rev
904
        self.revno = revno
905
        self.merge_depth = merge_depth
906
        self.delta = delta
907
        self.tags = tags
908
909
794 by Martin Pool
- Merge John's nice short-log format.
910
class LogFormatter(object):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
911
    """Abstract class to display log messages.
912
913
    At a minimum, a derived class must implement the log_revision method.
914
915
    If the LogFormatter needs to be informed of the beginning or end of
916
    a log it should implement the begin_log and/or end_log hook methods.
917
918
    A LogFormatter should define the following supports_XXX flags 
919
    to indicate which LogRevision attributes it supports:
920
921
    - supports_delta must be True if this log formatter supports delta.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
922
        Otherwise the delta attribute may not be populated.  The 'delta_format'
923
        attribute describes whether the 'short_status' format (1) or the long
3936.3.2 by Ian Clatworthy
minor cleanups
924
        one (2) should be used.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
925
 
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
926
    - supports_merge_revisions must be True if this log formatter supports 
3936.3.2 by Ian Clatworthy
minor cleanups
927
        merge revisions.  If not, and if supports_single_merge_revision is
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
928
        also not True, then only mainline revisions will be passed to the 
929
        formatter.
930
    - supports_single_merge_revision must be True if this log formatter
931
        supports logging only a single merge revision.  This flag is
932
        only relevant if supports_merge_revisions is not True.
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
933
    - supports_tags must be True if this log formatter supports tags.
934
        Otherwise the tags attribute may not be populated.
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
935
936
    Plugins can register functions to show custom revision properties using
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
937
    the properties_handler_registry. The registered function
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
938
    must respect the following interface description:
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
939
        def my_show_properties(properties_dict):
940
            # code that returns a dict {'name':'value'} of the properties 
941
            # to be shown
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
942
    """
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
943
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
944
    def __init__(self, to_file, show_ids=False, show_timezone='original',
945
                 delta_format=None):
794 by Martin Pool
- Merge John's nice short-log format.
946
        self.to_file = to_file
947
        self.show_ids = show_ids
948
        self.show_timezone = show_timezone
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
949
        if delta_format is None:
950
            # Ensures backward compatibility
951
            delta_format = 2 # long format
952
        self.delta_format = delta_format
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
953
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
954
# TODO: uncomment this block after show() has been removed.
955
# Until then defining log_revision would prevent _show_log calling show() 
956
# in legacy formatters.
957
#    def log_revision(self, revision):
958
#        """Log a revision.
959
#
960
#        :param  revision:   The LogRevision to be logged.
961
#        """
962
#        raise NotImplementedError('not implemented in abstract base')
963
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
964
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
965
        name, address = config.parse_username(rev.committer)
966
        if name:
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
967
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
968
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
969
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
970
    def short_author(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
971
        name, address = config.parse_username(rev.get_apparent_author())
972
        if name:
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
973
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
974
        return address
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
975
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
976
    def show_properties(self, revision, indent):
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
977
        """Displays the custom properties returned by each registered handler.
978
        
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
979
        If a registered handler raises an error it is propagated.
3144.7.5 by Guillermo Gonzalez
* some improvements to the doctstring in show_properties method and in LogFormatter
980
        """
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
981
        for key, handler in properties_handler_registry.iteritems():
982
            for key, value in handler(revision).items():
983
                self.to_file.write(indent + key + ': ' + value + '\n')
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
984
2388.1.11 by Alexander Belchenko
changes after John's review
985
794 by Martin Pool
- Merge John's nice short-log format.
986
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
987
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
988
    supports_merge_revisions = True
989
    supports_delta = True
990
    supports_tags = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
991
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
992
    def log_revision(self, revision):
993
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
994
        indent = '    ' * revision.merge_depth
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
995
        to_file = self.to_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
996
        to_file.write(indent + '-' * 60 + '\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
997
        if revision.revno is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
998
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
999
        if revision.tags:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1000
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1001
        if self.show_ids:
3257.2.1 by Adeodato Simó
Add a space after "revision-id:" in log output.
1002
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1003
            to_file.write('\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1004
            for parent_id in revision.rev.parent_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1005
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
3144.7.11 by Guillermo Gonzalez
* updates LongLogFormatter to pass revision instead of the properties dict to show_properties method
1006
        self.show_properties(revision.rev, indent)
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1007
2671.5.7 by Lukáš Lalinsky
Rename get_author to get_apparent_author, revert the long log back to displaying the committer.
1008
        author = revision.rev.properties.get('author', None)
1009
        if author is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1010
            to_file.write(indent + 'author: %s\n' % (author,))
1011
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1012
1013
        branch_nick = revision.rev.properties.get('branch-nick', None)
1014
        if branch_nick is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1015
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1016
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1017
        date_str = format_date(revision.rev.timestamp,
1018
                               revision.rev.timezone or 0,
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1019
                               self.show_timezone)
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1020
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1021
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1022
        to_file.write(indent + 'message:\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1023
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1024
            to_file.write(indent + '  (no message)\n')
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1025
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1026
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1027
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1028
                to_file.write(indent + '  %s\n' % (l,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1029
        if revision.delta is not None:
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
1030
            # We don't respect delta_format for compatibility
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1031
            revision.delta.show(to_file, self.show_ids, indent=indent,
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
1032
                                short_status=False)
794 by Martin Pool
- Merge John's nice short-log format.
1033
1034
1035
class ShortLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1036
1037
    supports_delta = True
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1038
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1039
    supports_single_merge_revision = True
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1040
1041
    def log_revision(self, revision):
794 by Martin Pool
- Merge John's nice short-log format.
1042
        to_file = self.to_file
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
1043
        is_merge = ''
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1044
        if len(revision.rev.parent_ids) > 1:
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
1045
            is_merge = ' [merge]'
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1046
        tags = ''
1047
        if revision.tags:
3946.3.2 by Ian Clatworthy
add tests & NEWS item
1048
            tags = ' {%s}' % (', '.join(revision.tags))
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1049
1050
        to_file.write("%5s %s\t%s%s%s\n" % (revision.revno,
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1051
                self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1052
                format_date(revision.rev.timestamp,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1053
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
1054
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1055
                            show_offset=False),
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1056
                tags, is_merge))
794 by Martin Pool
- Merge John's nice short-log format.
1057
        if self.show_ids:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1058
            to_file.write('      revision-id:%s\n'
1059
                          % (revision.rev.revision_id,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1060
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1061
            to_file.write('      (no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
1062
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1063
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1064
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1065
                to_file.write('      %s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
1066
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1067
        if revision.delta is not None:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1068
            revision.delta.show(to_file, self.show_ids,
1069
                                short_status=self.delta_format==1)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1070
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
1071
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1072
1185.12.25 by Aaron Bentley
Added one-line log format
1073
class LineLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1074
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1075
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1076
    supports_single_merge_revision = True
1077
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1078
    def __init__(self, *args, **kwargs):
1079
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1080
        self._max_chars = terminal_width() - 1
1081
1185.12.25 by Aaron Bentley
Added one-line log format
1082
    def truncate(self, str, max_len):
1083
        if len(str) <= max_len:
1084
            return str
1085
        return str[:max_len-3]+'...'
1086
1087
    def date_string(self, rev):
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1088
        return format_date(rev.timestamp, rev.timezone or 0,
1185.12.25 by Aaron Bentley
Added one-line log format
1089
                           self.show_timezone, date_fmt="%Y-%m-%d",
1090
                           show_offset=False)
1091
1092
    def message(self, rev):
1093
        if not rev.message:
1094
            return '(no message)'
1095
        else:
1096
            return rev.message
1097
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1098
    def log_revision(self, revision):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1099
        self.to_file.write(self.log_string(revision.revno, revision.rev,
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1100
            self._max_chars, revision.tags))
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1101
        self.to_file.write('\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1102
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1103
    def log_string(self, revno, rev, max_chars, tags=None):
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1104
        """Format log info into one string. Truncate tail of string
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
1105
        :param  revno:      revision number or None.
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1106
                            Revision numbers counts from 1.
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1107
        :param  rev:        revision object
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1108
        :param  max_chars:  maximum length of resulting string
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1109
        :param  tags:       list of tags or None
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1110
        :return:            formatted truncated string
1111
        """
1112
        out = []
1113
        if revno:
1114
            # show revno only when is not None
3946.3.4 by Ian Clatworthy
minor cleanup
1115
            out.append("%s:" % revno)
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1116
        out.append(self.truncate(self.short_author(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
1117
        out.append(self.date_string(rev))
3946.3.3 by Ian Clatworthy
feedback from jelmer re position of tags in --line
1118
        if tags:
1119
            tag_str = '{%s}' % (', '.join(tags))
1120
            out.append(tag_str)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
1121
        out.append(rev.get_summary())
1185.12.25 by Aaron Bentley
Added one-line log format
1122
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
1123
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1124
1185.12.27 by Aaron Bentley
Use line log for pending merges
1125
def line_log(rev, max_chars):
1126
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1127
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
1128
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1129
1130
class LogFormatterRegistry(registry.Registry):
1131
    """Registry for log formatters"""
1132
1133
    def make_formatter(self, name, *args, **kwargs):
1134
        """Construct a formatter from arguments.
1135
1136
        :param name: Name of the formatter to construct.  'short', 'long' and
1137
            'line' are built-in.
1138
        """
1139
        return self.get(name)(*args, **kwargs)
1140
1141
    def get_default(self, branch):
1142
        return self.get(branch.get_config().log_format())
1143
1144
1145
log_formatter_registry = LogFormatterRegistry()
1146
1147
1148
log_formatter_registry.register('short', ShortLogFormatter,
1149
                                'Moderately short log format')
1150
log_formatter_registry.register('long', LongLogFormatter,
1151
                                'Detailed log format')
1152
log_formatter_registry.register('line', LineLogFormatter,
1153
                                'Log format with one line per revision')
1154
794 by Martin Pool
- Merge John's nice short-log format.
1155
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1156
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1157
    log_formatter_registry.register(name, formatter)
1158
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1159
794 by Martin Pool
- Merge John's nice short-log format.
1160
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1161
    """Construct a formatter from arguments.
1162
1185.12.27 by Aaron Bentley
Use line log for pending merges
1163
    name -- Name of the formatter to construct; currently 'long', 'short' and
1164
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1165
    """
794 by Martin Pool
- Merge John's nice short-log format.
1166
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1167
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
1168
    except KeyError:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1169
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1170
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1171
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1172
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1173
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1174
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1175
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1176
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1177
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1178
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1179
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1180
    """Show the change in revision history comparing the old revision history to the new one.
1181
1182
    :param branch: The branch where the revisions exist
1183
    :param old_rh: The old revision history
1184
    :param new_rh: The new revision history
1185
    :param to_file: A file to write the results to. If None, stdout will be used
1186
    """
1187
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
1188
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1189
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1190
    lf = log_formatter(log_format,
1191
                       show_ids=False,
1192
                       to_file=to_file,
1193
                       show_timezone='original')
1194
1195
    # This is the first index which is different between
1196
    # old and new
1197
    base_idx = None
1198
    for i in xrange(max(len(new_rh),
1199
                        len(old_rh))):
1200
        if (len(new_rh) <= i
1201
            or len(old_rh) <= i
1202
            or new_rh[i] != old_rh[i]):
1203
            base_idx = i
1204
            break
1205
1206
    if base_idx is None:
1207
        to_file.write('Nothing seems to have changed\n')
1208
        return
1209
    ## TODO: It might be nice to do something like show_log
1210
    ##       and show the merged entries. But since this is the
1211
    ##       removed revisions, it shouldn't be as important
1212
    if base_idx < len(old_rh):
1213
        to_file.write('*'*60)
1214
        to_file.write('\nRemoved Revisions:\n')
1215
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1216
            rev = branch.repository.get_revision(old_rh[i])
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1217
            lr = LogRevision(rev, i+1, 0, None)
1218
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1219
        to_file.write('*'*60)
1220
        to_file.write('\n\n')
1221
    if base_idx < len(new_rh):
1222
        to_file.write('Added Revisions:\n')
1223
        show_log(branch,
1224
                 lf,
1225
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1226
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1227
                 direction='forward',
1228
                 start_revision=base_idx+1,
1229
                 end_revision=len(new_rh),
1230
                 search=None)
1231
3144.7.4 by Guillermo Gonzalez
* move the function regisstry into a real Registry instead of a list
1232
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1233
def get_history_change(old_revision_id, new_revision_id, repository):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1234
    """Calculate the uncommon lefthand history between two revisions.
1235
1236
    :param old_revision_id: The original revision id.
1237
    :param new_revision_id: The new revision id.
3848.1.22 by Aaron Bentley
Fix spelling
1238
    :param repository: The repository to use for the calculation.
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1239
1240
    return old_history, new_history
1241
    """
3848.1.6 by Aaron Bentley
Implement get_history_change
1242
    old_history = []
1243
    old_revisions = set()
1244
    new_history = []
1245
    new_revisions = set()
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1246
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
1247
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
3848.1.6 by Aaron Bentley
Implement get_history_change
1248
    stop_revision = None
1249
    do_old = True
1250
    do_new = True
1251
    while do_new or do_old:
1252
        if do_new:
1253
            try:
1254
                new_revision = new_iter.next()
1255
            except StopIteration:
1256
                do_new = False
1257
            else:
1258
                new_history.append(new_revision)
1259
                new_revisions.add(new_revision)
1260
                if new_revision in old_revisions:
1261
                    stop_revision = new_revision
1262
                    break
1263
        if do_old:
1264
            try:
1265
                old_revision = old_iter.next()
1266
            except StopIteration:
1267
                do_old = False
1268
            else:
1269
                old_history.append(old_revision)
1270
                old_revisions.add(old_revision)
1271
                if old_revision in new_revisions:
1272
                    stop_revision = old_revision
1273
                    break
1274
    new_history.reverse()
1275
    old_history.reverse()
1276
    if stop_revision is not None:
1277
        new_history = new_history[new_history.index(stop_revision) + 1:]
1278
        old_history = old_history[old_history.index(stop_revision) + 1:]
1279
    return old_history, new_history
1280
1281
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1282
def show_branch_change(branch, output, old_revno, old_revision_id):
1283
    """Show the changes made to a branch.
1284
1285
    :param branch: The branch to show changes about.
1286
    :param output: A file-like object to write changes to.
1287
    :param old_revno: The revno of the old tip.
1288
    :param old_revision_id: The revision_id of the old tip.
1289
    """
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1290
    new_revno, new_revision_id = branch.last_revision_info()
1291
    old_history, new_history = get_history_change(old_revision_id,
1292
                                                  new_revision_id,
1293
                                                  branch.repository)
1294
    if old_history == [] and new_history == []:
1295
        output.write('Nothing seems to have changed\n')
1296
        return
1297
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1298
    log_format = log_formatter_registry.get_default(branch)
1299
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1300
    if old_history != []:
1301
        output.write('*'*60)
1302
        output.write('\nRemoved Revisions:\n')
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1303
        show_flat_log(branch.repository, old_history, old_revno, lf)
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1304
        output.write('*'*60)
1305
        output.write('\n\n')
1306
    if new_history != []:
3848.1.9 by Aaron Bentley
new/old sections are omitted as appropriate.
1307
        output.write('Added Revisions:\n')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1308
        start_revno = new_revno - len(new_history) + 1
1309
        show_log(branch, lf, None, verbose=False, direction='forward',
1310
                 start_revision=start_revno,)
1311
1312
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1313
def show_flat_log(repository, history, last_revno, lf):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1314
    """Show a simple log of the specified history.
1315
1316
    :param repository: The repository to retrieve revisions from.
1317
    :param history: A list of revision_ids indicating the lefthand history.
1318
    :param last_revno: The revno of the last revision_id in the history.
1319
    :param lf: The log formatter to use.
1320
    """
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1321
    start_revno = last_revno - len(history) + 1
1322
    revisions = repository.get_revisions(history)
1323
    for i, rev in enumerate(revisions):
1324
        lr = LogRevision(rev, i + last_revno, 0, None)
1325
        lf.log_revision(lr)
1326
1327
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1328
properties_handler_registry = registry.Registry()
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
1329
properties_handler_registry.register_lazy("foreign",
1330
                                          "bzrlib.foreign",
1331
                                          "show_foreign_properties")
1332
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1333
1334
# adapters which revision ids to log are filtered. When log is called, the
1335
# log_rev_iterator is adapted through each of these factory methods.
1336
# Plugins are welcome to mutate this list in any way they like - as long
1337
# as the overall behaviour is preserved. At this point there is no extensible
1338
# mechanism for getting parameters to each factory method, and until there is
1339
# this won't be considered a stable api.
1340
log_adapters = [
1341
    # core log logic
3642.1.7 by Robert Collins
Review feedback.
1342
    _make_batch_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1343
    # read revision objects
3642.1.7 by Robert Collins
Review feedback.
1344
    _make_revision_objects,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1345
    # filter on log messages
3642.1.7 by Robert Collins
Review feedback.
1346
    _make_search_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1347
    # generate deltas for things we will show
3642.1.7 by Robert Collins
Review feedback.
1348
    _make_delta_filter
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1349
    ]