~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
45
relative to its mainline parent, not the delta relative to the last
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
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
52
# TODO: option to show delta summaries for merged-in revisions
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
53
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
54
from itertools import izip
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
55
import re
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
56
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
57
from bzrlib import(
58
    registry,
59
    symbol_versioning,
60
    )
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
61
import bzrlib.errors as errors
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
62
from bzrlib.symbol_versioning import deprecated_method, zero_eleven
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
63
from bzrlib.trace import mutter
2359.1.2 by Kent Gibson
add logging of merge revisions
64
from bzrlib.tsort import(
65
    merge_sort,
66
    topo_sort,
67
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
68
375 by Martin Pool
- New command touching-revisions and function to trace
69
70
def find_touching_revisions(branch, file_id):
71
    """Yield a description of revisions which affect the file_id.
72
73
    Each returned element is (revno, revision_id, description)
74
75
    This is the list of revisions where the file is either added,
76
    modified, renamed or deleted.
77
78
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
79
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
80
    """
81
    last_ie = None
82
    last_path = None
83
    revno = 1
84
    for revision_id in branch.revision_history():
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
85
        this_inv = branch.repository.get_revision_inventory(revision_id)
375 by Martin Pool
- New command touching-revisions and function to trace
86
        if file_id in this_inv:
87
            this_ie = this_inv[file_id]
88
            this_path = this_inv.id2path(file_id)
89
        else:
90
            this_ie = this_path = None
91
92
        # now we know how it was last time, and how it is in this revision.
93
        # are those two states effectively the same or not?
94
95
        if not this_ie and not last_ie:
96
            # not present in either
97
            pass
98
        elif this_ie and not last_ie:
99
            yield revno, revision_id, "added " + this_path
100
        elif not this_ie and last_ie:
101
            # deleted here
102
            yield revno, revision_id, "deleted " + last_path
103
        elif this_path != last_path:
104
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
105
        elif (this_ie.text_size != last_ie.text_size
106
              or this_ie.text_sha1 != last_ie.text_sha1):
107
            yield revno, revision_id, "modified " + this_path
108
109
        last_ie = this_ie
110
        last_path = this_path
111
        revno += 1
112
113
527 by Martin Pool
- refactor log command
114
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
115
def _enumerate_history(branch):
116
    rh = []
117
    revno = 1
118
    for rev_id in branch.revision_history():
119
        rh.append((revno, rev_id))
120
        revno += 1
121
    return rh
122
123
378 by Martin Pool
- New usage bzr log FILENAME
124
def show_log(branch,
794 by Martin Pool
- Merge John's nice short-log format.
125
             lf,
527 by Martin Pool
- refactor log command
126
             specific_fileid=None,
378 by Martin Pool
- New usage bzr log FILENAME
127
             verbose=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
128
             direction='reverse',
129
             start_revision=None,
900 by Martin Pool
- patch from john to search for matching commits
130
             end_revision=None,
131
             search=None):
369 by Martin Pool
- Split out log printing into new show_log function
132
    """Write out human-readable log of commits to this branch.
133
794 by Martin Pool
- Merge John's nice short-log format.
134
    lf
135
        LogFormatter object to show the output.
136
527 by Martin Pool
- refactor log command
137
    specific_fileid
378 by Martin Pool
- New usage bzr log FILENAME
138
        If true, list only the commits affecting the specified
139
        file, rather than all commits.
140
369 by Martin Pool
- Split out log printing into new show_log function
141
    verbose
142
        If true show added/changed/deleted/renamed files.
143
527 by Martin Pool
- refactor log command
144
    direction
145
        'reverse' (default) is latest to earliest;
146
        'forward' is earliest to latest.
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
147
148
    start_revision
149
        If not None, only show revisions >= start_revision
150
151
    end_revision
152
        If not None, only show revisions <= end_revision
369 by Martin Pool
- Split out log printing into new show_log function
153
    """
1417.1.7 by Robert Collins
teach log it needs a read lock
154
    branch.lock_read()
155
    try:
1756.1.6 by Aaron Bentley
Revert locking fix
156
        _show_log(branch, lf, specific_fileid, verbose, direction,
157
                  start_revision, end_revision, search)
1417.1.7 by Robert Collins
teach log it needs a read lock
158
    finally:
159
        branch.unlock()
160
    
161
def _show_log(branch,
162
             lf,
163
             specific_fileid=None,
164
             verbose=False,
165
             direction='reverse',
166
             start_revision=None,
167
             end_revision=None,
168
             search=None):
169
    """Worker function for show_log - see show_log."""
794 by Martin Pool
- Merge John's nice short-log format.
170
    from bzrlib.osutils import format_date
171
    from bzrlib.errors import BzrCheckError
172
    
173
    from warnings import warn
369 by Martin Pool
- Split out log printing into new show_log function
174
794 by Martin Pool
- Merge John's nice short-log format.
175
    if not isinstance(lf, LogFormatter):
176
        warn("not a LogFormatter instance: %r" % lf)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
177
178
    if specific_fileid:
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
179
        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
180
900 by Martin Pool
- patch from john to search for matching commits
181
    if search is not None:
182
        import re
183
        searchRE = re.compile(search, re.IGNORECASE)
184
    else:
185
        searchRE = None
186
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
187
    which_revs = _enumerate_history(branch)
188
    
189
    if start_revision is None:
190
        start_revision = 1
974.1.54 by aaron.bentley at utoronto
Fixed the revno bug in log
191
    else:
192
        branch.check_real_revno(start_revision)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
193
    
194
    if end_revision is None:
195
        end_revision = len(which_revs)
974.1.54 by aaron.bentley at utoronto
Fixed the revno bug in log
196
    else:
197
        branch.check_real_revno(end_revision)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
198
199
    # list indexes are 0-based; revisions are 1-based
200
    cut_revs = which_revs[(start_revision-1):(end_revision)]
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
201
    if not cut_revs:
202
        return
1756.2.18 by Aaron Bentley
Factor out the revision list generation
203
204
    # convert the revision history to a dictionary:
1756.2.27 by Aaron Bentley
Tweak rev_nos style
205
    rev_nos = dict((k, v) for v, k in cut_revs)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
206
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
207
    # override the mainline to look like the revision history.
208
    mainline_revs = [revision_id for index, revision_id in cut_revs]
209
    if cut_revs[0][0] == 1:
210
        mainline_revs.insert(0, None)
211
    else:
212
        mainline_revs.insert(0, which_revs[start_revision-2][1])
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
213
    # how should we show merged revisions ?
214
    # old api: show_merge. New api: show_merge_revno
215
    show_merge_revno = getattr(lf, 'show_merge_revno', None)
216
    show_merge = getattr(lf, 'show_merge', None)
217
    if show_merge is None and show_merge_revno is None:
218
        # no merged-revno support
219
        include_merges = False
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
220
    else:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
221
        include_merges = True
222
    if show_merge is not None and show_merge_revno is None:
223
        # tell developers to update their code
224
        symbol_versioning.warn('LogFormatters should provide show_merge_revno '
225
            'instead of show_merge since bzr 0.11.',
226
            DeprecationWarning, stacklevel=3)
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
227
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
228
                          direction, include_merges=include_merges)
229
    if specific_fileid:
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
230
        view_revisions = _get_revisions_touching_file_id(branch,
231
                                                         specific_fileid,
232
                                                         mainline_revs,
233
                                                         view_revs_iter)
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
234
    else:
235
        view_revisions = list(view_revs_iter)
2388.1.11 by Alexander Belchenko
changes after John's review
236
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
237
    use_tags = getattr(lf, 'supports_tags', False)
238
    if use_tags:
239
        rev_tag_dict = {}
240
        if branch.supports_tags():
241
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
2388.1.11 by Alexander Belchenko
changes after John's review
242
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
243
    def iter_revisions():
1756.3.22 by Aaron Bentley
Tweaks from review
244
        # r = revision, n = revno, d = merge depth
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
245
        revision_ids = [r for r, n, d in view_revisions]
1756.3.2 by Aaron Bentley
Refactor revision_delta call
246
        zeros = set(r for r, n, d in view_revisions if d == 0)
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
247
        num = 9
1756.3.22 by Aaron Bentley
Tweaks from review
248
        repository = branch.repository
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
249
        while revision_ids:
1756.3.22 by Aaron Bentley
Tweaks from review
250
            cur_deltas = {}
251
            revisions = repository.get_revisions(revision_ids[:num])
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
252
            if verbose:
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
253
                delta_revisions = [r for r in revisions if
254
                                   r.revision_id in zeros]
1756.3.22 by Aaron Bentley
Tweaks from review
255
                deltas = repository.get_deltas_for_revisions(delta_revisions)
256
                cur_deltas = dict(izip((r.revision_id for r in 
257
                                        delta_revisions), deltas))
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
258
            for revision in revisions:
1756.3.22 by Aaron Bentley
Tweaks from review
259
                # The delta value will be None unless
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
260
                # 1. verbose is specified, and
1756.3.22 by Aaron Bentley
Tweaks from review
261
                # 2. the revision is a mainline revision
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
262
                yield revision, cur_deltas.get(revision.revision_id)
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
263
            revision_ids  = revision_ids[num:]
2359.1.2 by Kent Gibson
add logging of merge revisions
264
            num = min(int(num * 1.5), 200)
1756.2.13 by Aaron Bentley
Used scaled iterator to retrive revisions
265
            
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
266
    # now we just print all the revisions
1756.3.2 by Aaron Bentley
Refactor revision_delta call
267
    for ((rev_id, revno, merge_depth), (rev, delta)) in \
1756.2.18 by Aaron Bentley
Factor out the revision list generation
268
         izip(view_revisions, iter_revisions()):
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
269
270
        if searchRE:
271
            if not searchRE.search(rev.message):
272
                continue
273
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
274
        if merge_depth == 0:
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
275
            if use_tags:
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
276
                lf.show(revno, rev, delta, rev_tag_dict.get(rev_id))
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
277
            else:
278
                lf.show(revno, rev, delta)
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
279
        else:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
280
            if show_merge_revno is None:
281
                lf.show_merge(rev, merge_depth)
282
            else:
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
283
                if use_tags:
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
284
                    lf.show_merge_revno(rev, merge_depth, revno,
285
                                        rev_tag_dict.get(rev_id))
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
286
                else:
287
                    lf.show_merge_revno(rev, merge_depth, revno)
527 by Martin Pool
- refactor log command
288
530 by Martin Pool
- put back verbose log support for reversed logs
289
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
290
def _get_revisions_touching_file_id(branch, file_id, mainline_revisions,
291
                                    view_revs_iter):
292
    """Return the list of revision ids which touch a given file id.
293
294
    This includes the revisions which directly change the file id,
295
    and the revisions which merge these changes. So if the
296
    revision graph is::
297
        A
298
        |\
299
        B C
300
        |/
301
        D
302
303
    And 'C' changes a file, then both C and D will be returned.
304
305
    This will also can be restricted based on a subset of the mainline.
2359.1.8 by John Arbash Meinel
doc
306
307
    :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.
308
    """
309
    # 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.
310
    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.
311
                branch.repository.get_transaction())
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
312
    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.
313
    # build the ancestry of each revision in the graph
314
    # - only listing the ancestors that change the specific file.
315
    rev_graph = branch.repository.get_revision_graph(mainline_revisions[-1])
316
    sorted_rev_list = topo_sort(rev_graph)
317
    ancestry = {}
318
    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
319
        parents = rev_graph[rev]
320
        if rev not in weave_modifed_revisions and len(parents) == 1:
321
            # We will not be adding anything new, so just use a reference to
322
            # the parent ancestry.
323
            rev_ancestry = ancestry[parents[0]]
324
        else:
325
            rev_ancestry = set()
326
            if rev in weave_modifed_revisions:
327
                rev_ancestry.add(rev)
328
            for parent in parents:
329
                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.
330
        ancestry[rev] = rev_ancestry
331
2359.1.5 by John Arbash Meinel
change some variable names to make the function a bit clearer.
332
    def is_merging_rev(r):
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
333
        parents = rev_graph[r]
334
        if len(parents) > 1:
335
            leftparent = parents[0]
336
            for rightparent in parents[1:]:
337
                if not ancestry[leftparent].issuperset(
338
                        ancestry[rightparent]):
339
                    return True
340
        return False
341
342
    # filter from the view the revisions that did not change or merge 
343
    # the specific file
344
    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.
345
            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.
346
347
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
348
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
349
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
350
    """Produce an iterator of revisions to show
351
    :return: an iterator of (revision_id, revno, merge_depth)
352
    (if there is no revno for a revision, None is supplied)
353
    """
1756.2.22 by Aaron Bentley
Apply review comments
354
    if include_merges is False:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
355
        revision_ids = mainline_revs[1:]
356
        if direction == 'reverse':
357
            revision_ids.reverse()
358
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
359
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
360
        return
1756.2.18 by Aaron Bentley
Factor out the revision list generation
361
    merge_sorted_revisions = merge_sort(
362
        branch.repository.get_revision_graph(mainline_revs[-1]),
363
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
364
        mainline_revs,
365
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
366
367
    if direction == 'forward':
368
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
369
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
370
    elif direction != 'reverse':
371
        raise ValueError('invalid direction %r' % direction)
372
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
373
    for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
374
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
375
376
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
377
def reverse_by_depth(merge_sorted_revisions, _depth=0):
378
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
379
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
380
    Revisions with a different depth are sorted as a group with the previous
381
    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
382
    but it looks much nicer.
383
    """
384
    zd_revisions = []
385
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
386
        if val[2] == _depth:
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
387
            zd_revisions.append([val])
388
        else:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
389
            assert val[2] > _depth
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
390
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
391
    for revisions in zd_revisions:
392
        if len(revisions) > 1:
393
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
394
    zd_revisions.reverse()
395
    result = []
396
    for chunk in zd_revisions:
397
        result.extend(chunk)
398
    return result
399
400
794 by Martin Pool
- Merge John's nice short-log format.
401
class LogFormatter(object):
402
    """Abstract class to display log messages."""
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
403
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
404
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
794 by Martin Pool
- Merge John's nice short-log format.
405
        self.to_file = to_file
406
        self.show_ids = show_ids
407
        self.show_timezone = show_timezone
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
408
409
    def show(self, revno, rev, delta):
410
        raise NotImplementedError('not implemented in abstract base')
1393.1.56 by Martin Pool
- doc and small refactoring of log code
411
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
412
    def short_committer(self, rev):
413
        return re.sub('<.*@.*>', '', rev.committer).strip(' ')
2388.1.11 by Alexander Belchenko
changes after John's review
414
415
794 by Martin Pool
- Merge John's nice short-log format.
416
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
417
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
418
    supports_tags = True    # must exist and be True
419
                            # if this log formatter support tags.
420
                            # .show() and .show_merge_revno() must then accept
421
                            # the 'tags'-argument with list of tags
422
423
    def show(self, revno, rev, delta, tags=None):
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
424
        return self._show_helper(revno=revno, rev=rev, delta=delta, tags=tags)
794 by Martin Pool
- Merge John's nice short-log format.
425
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
426
    @deprecated_method(zero_eleven)
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
427
    def show_merge(self, rev, merge_depth):
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
428
        return self._show_helper(rev=rev, indent='    '*merge_depth,
429
                                 merged=True, delta=None)
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
430
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
431
    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,
432
        """Show a merged revision rev, with merge_depth and a revno."""
433
        return self._show_helper(rev=rev, revno=revno,
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
434
            indent='    '*merge_depth, merged=True, delta=None, tags=tags)
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
435
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
436
    def _show_helper(self, rev=None, revno=None, indent='', merged=False,
437
                     delta=None, tags=None):
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
438
        """Show a revision, either merged or not."""
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
439
        from bzrlib.osutils import format_date
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
440
        to_file = self.to_file
441
        print >>to_file,  indent+'-' * 60
1185.35.18 by Aaron Bentley
Refactored long-format log printing
442
        if revno is not None:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
443
            print >>to_file,  indent+'revno:', revno
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
444
        if tags:
445
            print >>to_file, indent+'tags: %s' % (', '.join(tags))
1185.35.18 by Aaron Bentley
Refactored long-format log printing
446
        if merged:
447
            print >>to_file,  indent+'merged:', rev.revision_id
448
        elif self.show_ids:
449
            print >>to_file,  indent+'revision-id:', rev.revision_id
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
450
        if self.show_ids:
451
            for parent_id in rev.parent_ids:
452
                print >>to_file, indent+'parent:', parent_id
453
        print >>to_file,  indent+'committer:', rev.committer
2388.1.11 by Alexander Belchenko
changes after John's review
454
1185.35.17 by Aaron Bentley
Added branch nicks to long-format logs
455
        try:
456
            print >>to_file, indent+'branch nick: %s' % \
457
                rev.properties['branch-nick']
458
        except KeyError:
459
            pass
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
460
        date_str = format_date(rev.timestamp,
461
                               rev.timezone or 0,
462
                               self.show_timezone)
463
        print >>to_file,  indent+'timestamp: %s' % date_str
464
465
        print >>to_file,  indent+'message:'
466
        if not rev.message:
467
            print >>to_file,  indent+'  (no message)'
468
        else:
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
469
            message = rev.message.rstrip('\r\n')
470
            for l in message.split('\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.
471
                print >>to_file,  indent+'  ' + l
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
472
        if delta is not None:
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
473
            delta.show(to_file, self.show_ids)
794 by Martin Pool
- Merge John's nice short-log format.
474
475
476
class ShortLogFormatter(LogFormatter):
477
    def show(self, revno, rev, delta):
478
        from bzrlib.osutils import format_date
479
480
        to_file = self.to_file
1185.12.25 by Aaron Bentley
Added one-line log format
481
        date_str = format_date(rev.timestamp, rev.timezone or 0,
482
                            self.show_timezone)
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
483
        print >>to_file, "%5s %s\t%s" % (revno, self.short_committer(rev),
794 by Martin Pool
- Merge John's nice short-log format.
484
                format_date(rev.timestamp, rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
485
                            self.show_timezone, date_fmt="%Y-%m-%d",
486
                           show_offset=False))
794 by Martin Pool
- Merge John's nice short-log format.
487
        if self.show_ids:
488
            print >>to_file,  '      revision-id:', rev.revision_id
489
        if not rev.message:
490
            print >>to_file,  '      (no message)'
491
        else:
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
492
            message = rev.message.rstrip('\r\n')
493
            for l in message.split('\n'):
794 by Martin Pool
- Merge John's nice short-log format.
494
                print >>to_file,  '      ' + l
495
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
496
        # TODO: Why not show the modified files in a shorter form as
497
        # well? rewrap them single lines of appropriate length
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
498
        if delta is not None:
794 by Martin Pool
- Merge John's nice short-log format.
499
            delta.show(to_file, self.show_ids)
1185.31.21 by John Arbash Meinel
Added test for log formatting, found bug when redirecting short logs to a file instead of stdout.
500
        print >>to_file, ''
794 by Martin Pool
- Merge John's nice short-log format.
501
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
502
1185.12.25 by Aaron Bentley
Added one-line log format
503
class LineLogFormatter(LogFormatter):
504
    def truncate(self, str, max_len):
505
        if len(str) <= max_len:
506
            return str
507
        return str[:max_len-3]+'...'
508
509
    def date_string(self, rev):
510
        from bzrlib.osutils import format_date
511
        return format_date(rev.timestamp, rev.timezone or 0, 
512
                           self.show_timezone, date_fmt="%Y-%m-%d",
513
                           show_offset=False)
514
515
    def message(self, rev):
516
        if not rev.message:
517
            return '(no message)'
518
        else:
519
            return rev.message
520
521
    def show(self, revno, rev, delta):
1704.2.2 by Martin Pool
Detect terminal width using ioctl
522
        from bzrlib.osutils import terminal_width
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
523
        print >> self.to_file, self.log_string(revno, rev, terminal_width()-1)
1185.12.25 by Aaron Bentley
Added one-line log format
524
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
525
    def log_string(self, revno, rev, max_chars):
526
        """Format log info into one string. Truncate tail of string
527
        :param  revno:      revision number (int) or None.
528
                            Revision numbers counts from 1.
529
        :param  rev:        revision info object
530
        :param  max_chars:  maximum length of resulting string
531
        :return:            formatted truncated string
532
        """
533
        out = []
534
        if revno:
535
            # show revno only when is not None
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
536
            out.append("%s:" % revno)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
537
        out.append(self.truncate(self.short_committer(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
538
        out.append(self.date_string(rev))
1740.2.5 by Aaron Bentley
Merge from bzr.dev
539
        out.append(rev.get_summary())
1185.12.25 by Aaron Bentley
Added one-line log format
540
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
541
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
542
1185.12.27 by Aaron Bentley
Use line log for pending merges
543
def line_log(rev, max_chars):
544
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
545
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
546
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
547
548
class LogFormatterRegistry(registry.Registry):
549
    """Registry for log formatters"""
550
551
    def make_formatter(self, name, *args, **kwargs):
552
        """Construct a formatter from arguments.
553
554
        :param name: Name of the formatter to construct.  'short', 'long' and
555
            'line' are built-in.
556
        """
557
        return self.get(name)(*args, **kwargs)
558
559
    def get_default(self, branch):
560
        return self.get(branch.get_config().log_format())
561
562
563
log_formatter_registry = LogFormatterRegistry()
564
565
566
log_formatter_registry.register('short', ShortLogFormatter,
567
                                'Moderately short log format')
568
log_formatter_registry.register('long', LongLogFormatter,
569
                                'Detailed log format')
570
log_formatter_registry.register('line', LineLogFormatter,
571
                                'Log format with one line per revision')
572
794 by Martin Pool
- Merge John's nice short-log format.
573
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
574
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
575
    log_formatter_registry.register(name, formatter)
576
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
577
794 by Martin Pool
- Merge John's nice short-log format.
578
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
579
    """Construct a formatter from arguments.
580
1185.12.27 by Aaron Bentley
Use line log for pending merges
581
    name -- Name of the formatter to construct; currently 'long', 'short' and
582
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
583
    """
794 by Martin Pool
- Merge John's nice short-log format.
584
    from bzrlib.errors import BzrCommandError
585
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
586
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
587
    except KeyError:
794 by Martin Pool
- Merge John's nice short-log format.
588
        raise BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
589
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
590
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
591
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
592
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
593
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
594
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
595
596
def show_changed_revisions(branch, old_rh, new_rh, to_file=None, log_format='long'):
597
    """Show the change in revision history comparing the old revision history to the new one.
598
599
    :param branch: The branch where the revisions exist
600
    :param old_rh: The old revision history
601
    :param new_rh: The new revision history
602
    :param to_file: A file to write the results to. If None, stdout will be used
603
    """
604
    if to_file is None:
605
        import sys
606
        import codecs
607
        import bzrlib
608
        to_file = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
609
    lf = log_formatter(log_format,
610
                       show_ids=False,
611
                       to_file=to_file,
612
                       show_timezone='original')
613
614
    # This is the first index which is different between
615
    # old and new
616
    base_idx = None
617
    for i in xrange(max(len(new_rh),
618
                        len(old_rh))):
619
        if (len(new_rh) <= i
620
            or len(old_rh) <= i
621
            or new_rh[i] != old_rh[i]):
622
            base_idx = i
623
            break
624
625
    if base_idx is None:
626
        to_file.write('Nothing seems to have changed\n')
627
        return
628
    ## TODO: It might be nice to do something like show_log
629
    ##       and show the merged entries. But since this is the
630
    ##       removed revisions, it shouldn't be as important
631
    if base_idx < len(old_rh):
632
        to_file.write('*'*60)
633
        to_file.write('\nRemoved Revisions:\n')
634
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
635
            rev = branch.repository.get_revision(old_rh[i])
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
636
            lf.show(i+1, rev, None)
637
        to_file.write('*'*60)
638
        to_file.write('\n\n')
639
    if base_idx < len(new_rh):
640
        to_file.write('Added Revisions:\n')
641
        show_log(branch,
642
                 lf,
643
                 None,
644
                 verbose=True,
645
                 direction='forward',
646
                 start_revision=base_idx+1,
647
                 end_revision=len(new_rh),
648
                 search=None)
649