~bzr-pqm/bzr/bzr.dev

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
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
62
from bzrlib import (
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
63
    config,
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
64
    lazy_regex,
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
65
    registry,
66
    symbol_versioning,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
67
    )
68
from bzrlib.errors import (
69
    BzrCommandError,
70
    )
71
from bzrlib.osutils import (
72
    format_date,
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
73
    get_terminal_encoding,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
74
    terminal_width,
75
    )
2978.4.1 by Kent Gibson
Logging revision 0 returns error.
76
from bzrlib.revision import (
77
    NULL_REVISION,
78
    )
79
from bzrlib.revisionspec import (
80
    RevisionInfo,
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
81
    )
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
82
from bzrlib.symbol_versioning import (
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.
83
    deprecated_method,
84
    zero_seventeen,
85
    )
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
86
from bzrlib.trace import mutter
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
87
from bzrlib.tsort import (
2359.1.2 by Kent Gibson
add logging of merge revisions
88
    merge_sort,
89
    topo_sort,
90
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
91
375 by Martin Pool
- New command touching-revisions and function to trace
92
93
def find_touching_revisions(branch, file_id):
94
    """Yield a description of revisions which affect the file_id.
95
96
    Each returned element is (revno, revision_id, description)
97
98
    This is the list of revisions where the file is either added,
99
    modified, renamed or deleted.
100
101
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
102
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
103
    """
104
    last_ie = None
105
    last_path = None
106
    revno = 1
107
    for revision_id in branch.revision_history():
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
108
        this_inv = branch.repository.get_revision_inventory(revision_id)
375 by Martin Pool
- New command touching-revisions and function to trace
109
        if file_id in this_inv:
110
            this_ie = this_inv[file_id]
111
            this_path = this_inv.id2path(file_id)
112
        else:
113
            this_ie = this_path = None
114
115
        # now we know how it was last time, and how it is in this revision.
116
        # are those two states effectively the same or not?
117
118
        if not this_ie and not last_ie:
119
            # not present in either
120
            pass
121
        elif this_ie and not last_ie:
122
            yield revno, revision_id, "added " + this_path
123
        elif not this_ie and last_ie:
124
            # deleted here
125
            yield revno, revision_id, "deleted " + last_path
126
        elif this_path != last_path:
127
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
128
        elif (this_ie.text_size != last_ie.text_size
129
              or this_ie.text_sha1 != last_ie.text_sha1):
130
            yield revno, revision_id, "modified " + this_path
131
132
        last_ie = this_ie
133
        last_path = this_path
134
        revno += 1
135
136
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
137
def _enumerate_history(branch):
138
    rh = []
139
    revno = 1
140
    for rev_id in branch.revision_history():
141
        rh.append((revno, rev_id))
142
        revno += 1
143
    return rh
144
145
378 by Martin Pool
- New usage bzr log FILENAME
146
def show_log(branch,
794 by Martin Pool
- Merge John's nice short-log format.
147
             lf,
527 by Martin Pool
- refactor log command
148
             specific_fileid=None,
378 by Martin Pool
- New usage bzr log FILENAME
149
             verbose=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
150
             direction='reverse',
151
             start_revision=None,
900 by Martin Pool
- patch from john to search for matching commits
152
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
153
             search=None,
154
             limit=None):
369 by Martin Pool
- Split out log printing into new show_log function
155
    """Write out human-readable log of commits to this branch.
156
794 by Martin Pool
- Merge John's nice short-log format.
157
    lf
158
        LogFormatter object to show the output.
159
527 by Martin Pool
- refactor log command
160
    specific_fileid
378 by Martin Pool
- New usage bzr log FILENAME
161
        If true, list only the commits affecting the specified
162
        file, rather than all commits.
163
369 by Martin Pool
- Split out log printing into new show_log function
164
    verbose
165
        If true show added/changed/deleted/renamed files.
166
527 by Martin Pool
- refactor log command
167
    direction
168
        'reverse' (default) is latest to earliest;
169
        'forward' is earliest to latest.
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
170
171
    start_revision
172
        If not None, only show revisions >= start_revision
173
174
    end_revision
175
        If not None, only show revisions <= end_revision
2466.9.1 by Kent Gibson
add bzr log --limit
176
177
    search
178
        If not None, only show revisions with matching commit messages
179
180
    limit
181
        If not None or 0, only show limit revisions
369 by Martin Pool
- Split out log printing into new show_log function
182
    """
1417.1.7 by Robert Collins
teach log it needs a read lock
183
    branch.lock_read()
184
    try:
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
185
        if getattr(lf, 'begin_log', None):
186
            lf.begin_log()
187
1756.1.6 by Aaron Bentley
Revert locking fix
188
        _show_log(branch, lf, specific_fileid, verbose, direction,
2466.9.1 by Kent Gibson
add bzr log --limit
189
                  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.
190
191
        if getattr(lf, 'end_log', None):
192
            lf.end_log()
1417.1.7 by Robert Collins
teach log it needs a read lock
193
    finally:
194
        branch.unlock()
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
195
1417.1.7 by Robert Collins
teach log it needs a read lock
196
def _show_log(branch,
197
             lf,
198
             specific_fileid=None,
199
             verbose=False,
200
             direction='reverse',
201
             start_revision=None,
202
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
203
             search=None,
204
             limit=None):
1417.1.7 by Robert Collins
teach log it needs a read lock
205
    """Worker function for show_log - see show_log."""
794 by Martin Pool
- Merge John's nice short-log format.
206
    if not isinstance(lf, LogFormatter):
207
        warn("not a LogFormatter instance: %r" % lf)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
208
209
    if specific_fileid:
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
210
        mutter('get log for file_id %r', specific_fileid)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
211
900 by Martin Pool
- patch from john to search for matching commits
212
    if search is not None:
213
        searchRE = re.compile(search, re.IGNORECASE)
214
    else:
215
        searchRE = None
216
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
217
    mainline_revs, rev_nos, start_rev_id, end_rev_id = \
218
        _get_mainline_revs(branch, start_revision, end_revision)
219
    if not mainline_revs:
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
220
        return
1756.2.18 by Aaron Bentley
Factor out the revision list generation
221
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
222
    if direction == 'reverse':
223
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
224
        
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
225
    legacy_lf = getattr(lf, 'log_revision', None) is 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.
226
    if legacy_lf:
227
        # pre-0.17 formatters use show for mainline revisions.
228
        # how should we show merged revisions ?
229
        #   pre-0.11 api: show_merge
230
        #   0.11-0.16 api: show_merge_revno
231
        show_merge_revno = getattr(lf, 'show_merge_revno', None)
232
        show_merge = getattr(lf, 'show_merge', None)
233
        if show_merge is None and show_merge_revno is None:
234
            # no merged-revno support
235
            generate_merge_revisions = False
236
        else:
237
            generate_merge_revisions = True
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
238
        # tell developers to update their code
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.
239
        symbol_versioning.warn('LogFormatters should provide log_revision '
240
            'instead of show and show_merge_revno since bzr 0.17.',
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
241
            DeprecationWarning, stacklevel=3)
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.
242
    else:
243
        generate_merge_revisions = getattr(lf, 'supports_merge_revisions', 
244
                                           False)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
245
    generate_single_revision = False
2985.1.1 by Aaron Bentley
Better behavior when user requests a log that cannot be viewed (Kent Gibson)
246
    if ((not generate_merge_revisions)
2978.3.2 by Kent Gibson
Use in rather than has_key
247
        and ((start_rev_id and (start_rev_id not in rev_nos))
248
            or (end_rev_id and (end_rev_id not in rev_nos)))):
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
249
        generate_single_revision = ((start_rev_id == end_rev_id)
250
            and getattr(lf, 'supports_single_merge_revision', False))
251
        if not generate_single_revision:
252
            raise BzrCommandError('Selected log formatter only supports '
253
                'mainline revisions.')
254
        generate_merge_revisions = generate_single_revision
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
255
    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.
256
                          direction, include_merges=generate_merge_revisions)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
257
    view_revisions = _filter_revision_range(list(view_revs_iter),
258
                                            start_rev_id,
259
                                            end_rev_id)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
260
    if view_revisions and generate_single_revision:
261
        view_revisions = view_revisions[0:1]
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
262
    if specific_fileid:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
263
        view_revisions = _filter_revisions_touching_file_id(branch,
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
264
                                                         specific_fileid,
265
                                                         mainline_revs,
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
266
                                                         view_revisions)
2388.1.11 by Alexander Belchenko
changes after John's review
267
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
268
    # rebase merge_depth - unless there are no revisions or 
269
    # either the first or last revision have merge_depth = 0.
270
    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
271
        min_depth = min([d for r,n,d in view_revisions])
272
        if min_depth != 0:
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
273
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
274
        
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.
275
    rev_tag_dict = {}
276
    generate_tags = getattr(lf, 'supports_tags', False)
277
    if generate_tags:
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
278
        if branch.supports_tags():
279
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
2388.1.11 by Alexander Belchenko
changes after John's review
280
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.
281
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
282
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
283
    def iter_revisions():
1756.3.22 by Aaron Bentley
Tweaks from review
284
        # r = revision, n = revno, d = merge depth
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
285
        revision_ids = [r for r, n, d in view_revisions]
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
286
        num = 9
1756.3.22 by Aaron Bentley
Tweaks from review
287
        repository = branch.repository
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
288
        while revision_ids:
1756.3.22 by Aaron Bentley
Tweaks from review
289
            cur_deltas = {}
290
            revisions = repository.get_revisions(revision_ids[:num])
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.
291
            if generate_delta:
2466.11.1 by Kent Gibson
Long log format reports deltas on merge revisions.
292
                deltas = repository.get_deltas_for_revisions(revisions)
293
                cur_deltas = dict(izip((r.revision_id for r in revisions),
294
                                       deltas))
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
295
            for revision in revisions:
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
296
                yield revision, cur_deltas.get(revision.revision_id)
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
297
            revision_ids  = revision_ids[num:]
2359.1.2 by Kent Gibson
add logging of merge revisions
298
            num = min(int(num * 1.5), 200)
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.
299
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
300
    # now we just print all the revisions
2466.9.1 by Kent Gibson
add bzr log --limit
301
    log_count = 0
1756.3.2 by Aaron Bentley
Refactor revision_delta call
302
    for ((rev_id, revno, merge_depth), (rev, delta)) in \
1756.2.18 by Aaron Bentley
Factor out the revision list generation
303
         izip(view_revisions, iter_revisions()):
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
304
305
        if searchRE:
306
            if not searchRE.search(rev.message):
307
                continue
308
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.
309
        if not legacy_lf:
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
310
            lr = LogRevision(rev, revno, merge_depth, delta,
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
311
                             rev_tag_dict.get(rev_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.
312
            lf.log_revision(lr)
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
313
        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.
314
            # support for legacy (pre-0.17) LogFormatters
315
            if merge_depth == 0:
316
                if generate_tags:
317
                    lf.show(revno, rev, delta, rev_tag_dict.get(rev_id))
318
                else:
319
                    lf.show(revno, rev, delta)
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
320
            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.
321
                if show_merge_revno is None:
322
                    lf.show_merge(rev, merge_depth)
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
323
                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.
324
                    if generate_tags:
325
                        lf.show_merge_revno(rev, merge_depth, revno,
326
                                            rev_tag_dict.get(rev_id))
327
                    else:
328
                        lf.show_merge_revno(rev, merge_depth, revno)
2466.9.1 by Kent Gibson
add bzr log --limit
329
        if limit:
330
            log_count += 1
331
            if log_count >= limit:
332
                break
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.
333
530 by Martin Pool
- put back verbose log support for reversed logs
334
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
335
def _get_mainline_revs(branch, start_revision, end_revision):
336
    """Get the mainline revisions from the branch.
337
    
338
    Generates the list of mainline revisions for the branch.
339
    
340
    :param  branch: The branch containing the revisions. 
341
342
    :param  start_revision: The first revision to be logged.
343
            For backwards compatibility this may be a mainline integer revno,
344
            but for merge revision support a RevisionInfo is expected.
345
346
    :param  end_revision: The last revision to be logged.
347
            For backwards compatibility this may be a mainline integer revno,
348
            but for merge revision support a RevisionInfo is expected.
349
350
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
351
    """
352
    which_revs = _enumerate_history(branch)
353
    if not which_revs:
354
        return None, None, None, None
355
356
    # For mainline generation, map start_revision and end_revision to 
357
    # mainline revnos. If the revision is not on the mainline choose the 
358
    # appropriate extreme of the mainline instead - the extra will be 
359
    # filtered later.
360
    # Also map the revisions to rev_ids, to be used in the later filtering
361
    # stage.
362
    start_rev_id = None 
363
    if start_revision is None:
364
        start_revno = 1
365
    else:
366
        if isinstance(start_revision,RevisionInfo):
367
            start_rev_id = start_revision.rev_id
368
            start_revno = start_revision.revno or 1
369
        else:
370
            branch.check_real_revno(start_revision)
371
            start_revno = start_revision
372
    
373
    end_rev_id = None
374
    if end_revision is None:
375
        end_revno = len(which_revs)
376
    else:
377
        if isinstance(end_revision,RevisionInfo):
378
            end_rev_id = end_revision.rev_id
379
            end_revno = end_revision.revno or len(which_revs)
380
        else:
381
            branch.check_real_revno(end_revision)
382
            end_revno = end_revision
383
2989.1.1 by Aaron Bentley
Merge Kent's revision 0 fix
384
    if ((start_rev_id == NULL_REVISION)
2978.4.1 by Kent Gibson
Logging revision 0 returns error.
385
        or (end_rev_id == NULL_REVISION)):
386
        raise BzrCommandError('Logging revision 0 is invalid.')
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
387
    if start_revno > end_revno:
388
        raise BzrCommandError("Start revision must be older than "
389
                              "the end revision.")
390
391
    # list indexes are 0-based; revisions are 1-based
392
    cut_revs = which_revs[(start_revno-1):(end_revno)]
393
    if not cut_revs:
394
        return None, None, None, None
395
396
    # convert the revision history to a dictionary:
397
    rev_nos = dict((k, v) for v, k in cut_revs)
398
399
    # override the mainline to look like the revision history.
400
    mainline_revs = [revision_id for index, revision_id in cut_revs]
401
    if cut_revs[0][0] == 1:
402
        mainline_revs.insert(0, None)
403
    else:
404
        mainline_revs.insert(0, which_revs[start_revno-2][1])
405
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
406
407
408
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
409
    """Filter view_revisions based on revision ranges.
410
411
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
412
            tuples to be filtered.
413
414
    :param start_rev_id: If not NONE specifies the first revision to be logged.
415
            If NONE then all revisions up to the end_rev_id are logged.
416
417
    :param end_rev_id: If not NONE specifies the last revision to be logged.
418
            If NONE then all revisions up to the end of the log are logged.
419
420
    :return: The filtered view_revisions.
421
    """
422
    if start_rev_id or end_rev_id: 
423
        revision_ids = [r for r, n, d in view_revisions]
424
        if start_rev_id:
425
            start_index = revision_ids.index(start_rev_id)
426
        else:
427
            start_index = 0
428
        if start_rev_id == end_rev_id:
429
            end_index = start_index
430
        else:
431
            if end_rev_id:
432
                end_index = revision_ids.index(end_rev_id)
433
            else:
434
                end_index = len(view_revisions) - 1
435
        # To include the revisions merged into the last revision, 
436
        # extend end_rev_id down to, but not including, the next rev
437
        # with the same or lesser merge_depth
438
        end_merge_depth = view_revisions[end_index][2]
439
        try:
440
            for index in xrange(end_index+1, len(view_revisions)+1):
441
                if view_revisions[index][2] <= end_merge_depth:
442
                    end_index = index - 1
443
                    break
444
        except IndexError:
445
            # if the search falls off the end then log to the end as well
446
            end_index = len(view_revisions) - 1
447
        view_revisions = view_revisions[start_index:end_index+1]
448
    return view_revisions
449
450
451
def _filter_revisions_touching_file_id(branch, file_id, mainline_revisions,
452
                                       view_revs_iter):
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
453
    """Return the list of revision ids which touch a given file id.
454
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
455
    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.
456
    This includes the revisions which directly change the file id,
457
    and the revisions which merge these changes. So if the
458
    revision graph is::
459
        A
460
        |\
461
        B C
462
        |/
463
        D
464
465
    And 'C' changes a file, then both C and D will be returned.
466
467
    This will also can be restricted based on a subset of the mainline.
2359.1.8 by John Arbash Meinel
doc
468
469
    :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.
470
    """
471
    # find all the revisions that change the specific file
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
472
    file_weave = branch.repository.weave_store.get_weave(file_id,
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
473
                branch.repository.get_transaction())
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
474
    weave_modifed_revisions = set(file_weave.versions())
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
475
    # build the ancestry of each revision in the graph
476
    # - only listing the ancestors that change the specific file.
477
    rev_graph = branch.repository.get_revision_graph(mainline_revisions[-1])
478
    sorted_rev_list = topo_sort(rev_graph)
479
    ancestry = {}
480
    for rev in sorted_rev_list:
2359.1.9 by John Arbash Meinel
Only generate a new set when we need to. Drops 'bzr log NEWS' time from 22s => 8s
481
        parents = rev_graph[rev]
482
        if rev not in weave_modifed_revisions and len(parents) == 1:
483
            # We will not be adding anything new, so just use a reference to
484
            # the parent ancestry.
485
            rev_ancestry = ancestry[parents[0]]
486
        else:
487
            rev_ancestry = set()
488
            if rev in weave_modifed_revisions:
489
                rev_ancestry.add(rev)
490
            for parent in parents:
491
                rev_ancestry = rev_ancestry.union(ancestry[parent])
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
492
        ancestry[rev] = rev_ancestry
493
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
494
    def is_merging_rev(r):
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
495
        parents = rev_graph[r]
496
        if len(parents) > 1:
497
            leftparent = parents[0]
498
            for rightparent in parents[1:]:
499
                if not ancestry[leftparent].issuperset(
500
                        ancestry[rightparent]):
501
                    return True
502
        return False
503
504
    # filter from the view the revisions that did not change or merge 
505
    # the specific file
506
    return [(r, n, d) for r, n, d in view_revs_iter
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
507
            if r in weave_modifed_revisions or is_merging_rev(r)]
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
508
509
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
510
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
511
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
512
    """Produce an iterator of revisions to show
513
    :return: an iterator of (revision_id, revno, merge_depth)
514
    (if there is no revno for a revision, None is supplied)
515
    """
1756.2.22 by Aaron Bentley
Apply review comments
516
    if include_merges is False:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
517
        revision_ids = mainline_revs[1:]
518
        if direction == 'reverse':
519
            revision_ids.reverse()
520
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
521
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
522
        return
1756.2.18 by Aaron Bentley
Factor out the revision list generation
523
    merge_sorted_revisions = merge_sort(
524
        branch.repository.get_revision_graph(mainline_revs[-1]),
525
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
526
        mainline_revs,
527
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
528
529
    if direction == 'forward':
530
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
531
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
532
    elif direction != 'reverse':
533
        raise ValueError('invalid direction %r' % direction)
534
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
535
    for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
536
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
537
538
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
539
def reverse_by_depth(merge_sorted_revisions, _depth=0):
540
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
541
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
542
    Revisions with a different depth are sorted as a group with the previous
543
    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
544
    but it looks much nicer.
545
    """
546
    zd_revisions = []
547
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
548
        if val[2] == _depth:
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
549
            zd_revisions.append([val])
550
        else:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
551
            assert val[2] > _depth
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
552
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
553
    for revisions in zd_revisions:
554
        if len(revisions) > 1:
555
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
556
    zd_revisions.reverse()
557
    result = []
558
    for chunk in zd_revisions:
559
        result.extend(chunk)
560
    return result
561
562
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.
563
class LogRevision(object):
564
    """A revision to be logged (by LogFormatter.log_revision).
565
566
    A simple wrapper for the attributes of a revision to be logged.
567
    The attributes may or may not be populated, as determined by the 
568
    logging options and the log formatter capabilities.
569
    """
570
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
571
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
572
                 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.
573
        self.rev = rev
574
        self.revno = revno
575
        self.merge_depth = merge_depth
576
        self.delta = delta
577
        self.tags = tags
578
579
794 by Martin Pool
- Merge John's nice short-log format.
580
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.
581
    """Abstract class to display log messages.
582
583
    At a minimum, a derived class must implement the log_revision method.
584
585
    If the LogFormatter needs to be informed of the beginning or end of
586
    a log it should implement the begin_log and/or end_log hook methods.
587
588
    A LogFormatter should define the following supports_XXX flags 
589
    to indicate which LogRevision attributes it supports:
590
591
    - supports_delta must be True if this log formatter supports delta.
592
        Otherwise the delta attribute may not be populated.
593
    - supports_merge_revisions must be True if this log formatter supports 
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
594
        merge revisions.  If not, and if supports_single_merge_revisions is
595
        also not True, then only mainline revisions will be passed to the 
596
        formatter.
597
    - supports_single_merge_revision must be True if this log formatter
598
        supports logging only a single merge revision.  This flag is
599
        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.
600
    - supports_tags must be True if this log formatter supports tags.
601
        Otherwise the tags attribute may not be populated.
602
    """
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
603
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
604
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
794 by Martin Pool
- Merge John's nice short-log format.
605
        self.to_file = to_file
606
        self.show_ids = show_ids
607
        self.show_timezone = show_timezone
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
608
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.
609
# TODO: uncomment this block after show() has been removed.
610
# Until then defining log_revision would prevent _show_log calling show() 
611
# in legacy formatters.
612
#    def log_revision(self, revision):
613
#        """Log a revision.
614
#
615
#        :param  revision:   The LogRevision to be logged.
616
#        """
617
#        raise NotImplementedError('not implemented in abstract base')
618
619
    @deprecated_method(zero_seventeen)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
620
    def show(self, revno, rev, delta):
621
        raise NotImplementedError('not implemented in abstract base')
1393.1.56 by Martin Pool
- doc and small refactoring of log code
622
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
623
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
624
        name, address = config.parse_username(rev.committer)
625
        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.
626
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
627
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
628
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.
629
    def short_author(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
630
        name, address = config.parse_username(rev.get_apparent_author())
631
        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.
632
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
633
        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.
634
2388.1.11 by Alexander Belchenko
changes after John's review
635
794 by Martin Pool
- Merge John's nice short-log format.
636
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
637
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.
638
    supports_merge_revisions = True
639
    supports_delta = True
640
    supports_tags = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
641
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.
642
    @deprecated_method(zero_seventeen)
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
643
    def show(self, revno, rev, delta, tags=None):
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
644
        lr = LogRevision(rev, revno, 0, delta, tags)
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.
645
        return self.log_revision(lr)
794 by Martin Pool
- Merge John's nice short-log format.
646
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.
647
    @deprecated_method(zero_seventeen)
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
648
    def show_merge_revno(self, rev, merge_depth, revno, tags=None):
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
649
        """Show a merged revision rev, with merge_depth and a revno."""
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
650
        lr = LogRevision(rev, revno, merge_depth, tags=tags)
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.
651
        return self.log_revision(lr)
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
652
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.
653
    def log_revision(self, revision):
654
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
655
        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.
656
        to_file = self.to_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
657
        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.
658
        if revision.revno is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
659
            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.
660
        if revision.tags:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
661
            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.
662
        if self.show_ids:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
663
            to_file.write(indent + 'revision-id:' + revision.rev.revision_id)
664
            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.
665
            for parent_id in revision.rev.parent_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
666
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
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.
667
2671.5.7 by Lukáš Lalinsky
Rename get_author to get_apparent_author, revert the long log back to displaying the committer.
668
        author = revision.rev.properties.get('author', None)
669
        if author is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
670
            to_file.write(indent + 'author: %s\n' % (author,))
671
        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.
672
673
        branch_nick = revision.rev.properties.get('branch-nick', None)
674
        if branch_nick is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
675
            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.
676
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.
677
        date_str = format_date(revision.rev.timestamp,
678
                               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.
679
                               self.show_timezone)
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
680
        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.
681
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
682
        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.
683
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
684
            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.
685
        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.
686
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
687
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
688
                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.
689
        if revision.delta is not None:
2466.11.1 by Kent Gibson
Long log format reports deltas on merge revisions.
690
            revision.delta.show(to_file, self.show_ids, indent=indent)
794 by Martin Pool
- Merge John's nice short-log format.
691
692
693
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.
694
695
    supports_delta = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
696
    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.
697
698
    @deprecated_method(zero_seventeen)
794 by Martin Pool
- Merge John's nice short-log format.
699
    def show(self, revno, rev, delta):
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
700
        lr = LogRevision(rev, revno, 0, delta)
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.
701
        return self.log_revision(lr)
702
703
    def log_revision(self, revision):
794 by Martin Pool
- Merge John's nice short-log format.
704
        to_file = self.to_file
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
705
        date_str = 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.
706
                               revision.rev.timezone or 0,
707
                               self.show_timezone)
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
708
        is_merge = ''
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
709
        if len(revision.rev.parent_ids) > 1:
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
710
            is_merge = ' [merge]'
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
711
        to_file.write("%5s %s\t%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.
712
                self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
713
                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.
714
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
715
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
716
                            show_offset=False),
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
717
                is_merge))
794 by Martin Pool
- Merge John's nice short-log format.
718
        if self.show_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
719
            to_file.write('      revision-id:%s\n' % (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.
720
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
721
            to_file.write('      (no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
722
        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.
723
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
724
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
725
                to_file.write('      %s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
726
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
727
        # TODO: Why not show the modified files in a shorter form as
728
        # well? rewrap them single lines of appropriate length
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.
729
        if revision.delta is not None:
730
            revision.delta.show(to_file, self.show_ids)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
731
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
732
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
733
1185.12.25 by Aaron Bentley
Added one-line log format
734
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.
735
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
736
    supports_single_merge_revision = True
737
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.
738
    def __init__(self, *args, **kwargs):
739
        super(LineLogFormatter, self).__init__(*args, **kwargs)
740
        self._max_chars = terminal_width() - 1
741
1185.12.25 by Aaron Bentley
Added one-line log format
742
    def truncate(self, str, max_len):
743
        if len(str) <= max_len:
744
            return str
745
        return str[:max_len-3]+'...'
746
747
    def date_string(self, rev):
748
        return format_date(rev.timestamp, rev.timezone or 0, 
749
                           self.show_timezone, date_fmt="%Y-%m-%d",
750
                           show_offset=False)
751
752
    def message(self, rev):
753
        if not rev.message:
754
            return '(no message)'
755
        else:
756
            return rev.message
757
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.
758
    @deprecated_method(zero_seventeen)
1185.12.25 by Aaron Bentley
Added one-line log format
759
    def show(self, revno, rev, delta):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
760
        self.to_file.write(self.log_string(revno, rev, terminal_width()-1))
761
        self.to_file.write('\n')
1185.12.25 by Aaron Bentley
Added one-line log format
762
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.
763
    def log_revision(self, revision):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
764
        self.to_file.write(self.log_string(revision.revno, revision.rev,
765
                                              self._max_chars))
766
        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.
767
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
768
    def log_string(self, revno, rev, max_chars):
769
        """Format log info into one string. Truncate tail of string
770
        :param  revno:      revision number (int) or None.
771
                            Revision numbers counts from 1.
772
        :param  rev:        revision info object
773
        :param  max_chars:  maximum length of resulting string
774
        :return:            formatted truncated string
775
        """
776
        out = []
777
        if revno:
778
            # show revno only when is not None
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
779
            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.
780
        out.append(self.truncate(self.short_author(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
781
        out.append(self.date_string(rev))
1740.2.5 by Aaron Bentley
Merge from bzr.dev
782
        out.append(rev.get_summary())
1185.12.25 by Aaron Bentley
Added one-line log format
783
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
784
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
785
1185.12.27 by Aaron Bentley
Use line log for pending merges
786
def line_log(rev, max_chars):
787
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
788
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
789
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
790
791
class LogFormatterRegistry(registry.Registry):
792
    """Registry for log formatters"""
793
794
    def make_formatter(self, name, *args, **kwargs):
795
        """Construct a formatter from arguments.
796
797
        :param name: Name of the formatter to construct.  'short', 'long' and
798
            'line' are built-in.
799
        """
800
        return self.get(name)(*args, **kwargs)
801
802
    def get_default(self, branch):
803
        return self.get(branch.get_config().log_format())
804
805
806
log_formatter_registry = LogFormatterRegistry()
807
808
809
log_formatter_registry.register('short', ShortLogFormatter,
810
                                'Moderately short log format')
811
log_formatter_registry.register('long', LongLogFormatter,
812
                                'Detailed log format')
813
log_formatter_registry.register('line', LineLogFormatter,
814
                                'Log format with one line per revision')
815
794 by Martin Pool
- Merge John's nice short-log format.
816
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
817
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
818
    log_formatter_registry.register(name, formatter)
819
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
820
794 by Martin Pool
- Merge John's nice short-log format.
821
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
822
    """Construct a formatter from arguments.
823
1185.12.27 by Aaron Bentley
Use line log for pending merges
824
    name -- Name of the formatter to construct; currently 'long', 'short' and
825
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
826
    """
794 by Martin Pool
- Merge John's nice short-log format.
827
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
828
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
829
    except KeyError:
794 by Martin Pool
- Merge John's nice short-log format.
830
        raise BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
831
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
832
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
833
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
834
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
835
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
836
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
837
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
838
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
839
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
840
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
841
    """Show the change in revision history comparing the old revision history to the new one.
842
843
    :param branch: The branch where the revisions exist
844
    :param old_rh: The old revision history
845
    :param new_rh: The new revision history
846
    :param to_file: A file to write the results to. If None, stdout will be used
847
    """
848
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
849
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
850
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
851
    lf = log_formatter(log_format,
852
                       show_ids=False,
853
                       to_file=to_file,
854
                       show_timezone='original')
855
856
    # This is the first index which is different between
857
    # old and new
858
    base_idx = None
859
    for i in xrange(max(len(new_rh),
860
                        len(old_rh))):
861
        if (len(new_rh) <= i
862
            or len(old_rh) <= i
863
            or new_rh[i] != old_rh[i]):
864
            base_idx = i
865
            break
866
867
    if base_idx is None:
868
        to_file.write('Nothing seems to have changed\n')
869
        return
870
    ## TODO: It might be nice to do something like show_log
871
    ##       and show the merged entries. But since this is the
872
    ##       removed revisions, it shouldn't be as important
873
    if base_idx < len(old_rh):
874
        to_file.write('*'*60)
875
        to_file.write('\nRemoved Revisions:\n')
876
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
877
            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
878
            lr = LogRevision(rev, i+1, 0, None)
879
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
880
        to_file.write('*'*60)
881
        to_file.write('\n\n')
882
    if base_idx < len(new_rh):
883
        to_file.write('Added Revisions:\n')
884
        show_log(branch,
885
                 lf,
886
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
887
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
888
                 direction='forward',
889
                 start_revision=base_idx+1,
890
                 end_revision=len(new_rh),
891
                 search=None)
892