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