1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
"""Code to show logs of changes.
21
Various flavors of log can be produced:
23
* for one file, or the whole tree, and (not done yet) for
24
files in a given directory
26
* in "verbose" mode with a description of what changed from one
29
* with file-ids and revision-ids shown
31
Logs are actually written out through an abstract LogFormatter
32
interface, which allows for different preferred formats. Plugins can
35
Logs can be produced in either forward (oldest->newest) or reverse
36
(newest->oldest) order.
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
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 left-most 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.
53
from cStringIO import StringIO
54
from itertools import (
60
from warnings import (
64
from bzrlib.lazy_import import lazy_import
65
lazy_import(globals(), """
72
repository as _mod_repository,
73
revision as _mod_revision,
83
from bzrlib.osutils import (
85
get_terminal_encoding,
91
def find_touching_revisions(branch, file_id):
92
"""Yield a description of revisions which affect the file_id.
94
Each returned element is (revno, revision_id, description)
96
This is the list of revisions where the file is either added,
97
modified, renamed or deleted.
99
TODO: Perhaps some way to limit this to only particular revisions,
100
or to traverse a non-mainline set of revisions?
105
for revision_id in branch.revision_history():
106
this_inv = branch.repository.get_revision_inventory(revision_id)
107
if file_id in this_inv:
108
this_ie = this_inv[file_id]
109
this_path = this_inv.id2path(file_id)
111
this_ie = this_path = None
113
# now we know how it was last time, and how it is in this revision.
114
# are those two states effectively the same or not?
116
if not this_ie and not last_ie:
117
# not present in either
119
elif this_ie and not last_ie:
120
yield revno, revision_id, "added " + this_path
121
elif not this_ie and last_ie:
123
yield revno, revision_id, "deleted " + last_path
124
elif this_path != last_path:
125
yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
126
elif (this_ie.text_size != last_ie.text_size
127
or this_ie.text_sha1 != last_ie.text_sha1):
128
yield revno, revision_id, "modified " + this_path
131
last_path = this_path
135
def _enumerate_history(branch):
138
for rev_id in branch.revision_history():
139
rh.append((revno, rev_id))
146
specific_fileid=None,
154
"""Write out human-readable log of commits to this branch.
156
This function is being retained for backwards compatibility but
157
should not be extended with new parameters. Use the new Logger class
158
instead, eg. Logger(branch, rqst).show(lf), adding parameters to the
159
make_log_request_dict function.
161
:param lf: The LogFormatter object showing the output.
163
:param specific_fileid: If not None, list only the commits affecting the
164
specified file, rather than all commits.
166
:param verbose: If True show added/changed/deleted/renamed files.
168
:param direction: 'reverse' (default) is latest to earliest; 'forward' is
171
:param start_revision: If not None, only show revisions >= start_revision
173
:param end_revision: If not None, only show revisions <= end_revision
175
:param search: If not None, only show revisions with matching commit
178
:param limit: If set, shows only 'limit' revisions, all revisions are shown
181
:param show_diff: If True, output a diff after each revision.
183
# Convert old-style parameters to new-style parameters
184
if specific_fileid is not None:
185
file_ids = [specific_fileid]
190
delta_type = 'partial'
197
diff_type = 'partial'
203
# Build the request and execute it
204
rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
205
start_revision=start_revision, end_revision=end_revision,
206
limit=limit, message_search=search,
207
delta_type=delta_type, diff_type=diff_type)
208
Logger(branch, rqst).show(lf)
211
# Note: This needs to be kept this in sync with the defaults in
212
# make_log_request_dict() below
213
_DEFAULT_REQUEST_PARAMS = {
214
'direction': 'reverse',
216
'generate_tags': True,
217
'_match_using_deltas': True,
221
def make_log_request_dict(direction='reverse', specific_fileids=None,
222
start_revision=None, end_revision=None, limit=None,
223
message_search=None, levels=1, generate_tags=True, delta_type=None,
224
diff_type=None, _match_using_deltas=True):
225
"""Convenience function for making a logging request dictionary.
227
Using this function may make code slightly safer by ensuring
228
parameters have the correct names. It also provides a reference
229
point for documenting the supported parameters.
231
:param direction: 'reverse' (default) is latest to earliest;
232
'forward' is earliest to latest.
234
:param specific_fileids: If not None, only include revisions
235
affecting the specified files, rather than all revisions.
237
:param start_revision: If not None, only generate
238
revisions >= start_revision
240
:param end_revision: If not None, only generate
241
revisions <= end_revision
243
:param limit: If set, generate only 'limit' revisions, all revisions
244
are shown if None or 0.
246
:param message_search: If not None, only include revisions with
247
matching commit messages
249
:param levels: the number of levels of revisions to
250
generate; 1 for just the mainline; 0 for all levels.
252
:param generate_tags: If True, include tags for matched revisions.
254
:param delta_type: Either 'full', 'partial' or None.
255
'full' means generate the complete delta - adds/deletes/modifies/etc;
256
'partial' means filter the delta using specific_fileids;
257
None means do not generate any delta.
259
:param diff_type: Either 'full', 'partial' or None.
260
'full' means generate the complete diff - adds/deletes/modifies/etc;
261
'partial' means filter the diff using specific_fileids;
262
None means do not generate any diff.
264
:param _match_using_deltas: a private parameter controlling the
265
algorithm used for matching specific_fileids. This parameter
266
may be removed in the future so bzrlib client code should NOT
270
'direction': direction,
271
'specific_fileids': specific_fileids,
272
'start_revision': start_revision,
273
'end_revision': end_revision,
275
'message_search': message_search,
277
'generate_tags': generate_tags,
278
'delta_type': delta_type,
279
'diff_type': diff_type,
280
# Add 'private' attributes for features that may be deprecated
281
'_match_using_deltas': _match_using_deltas,
282
'_allow_single_merge_revision': True,
286
def _apply_log_request_defaults(rqst):
287
"""Apply default values to a request dictionary."""
288
result = _DEFAULT_REQUEST_PARAMS
294
class LogGenerator(object):
295
"""A generator of log revisions."""
297
def iter_log_revisions(self):
298
"""Iterate over LogRevision objects.
300
:return: An iterator yielding LogRevision objects.
302
raise NotImplementedError(self.iter_log_revisions)
305
class Logger(object):
306
"""An object the generates, formats and displays a log."""
308
def __init__(self, branch, rqst):
311
:param branch: the branch to log
312
:param rqst: A dictionary specifying the query parameters.
313
See make_log_request_dict() for supported values.
316
self.rqst = _apply_log_request_defaults(rqst)
321
:param lf: The LogFormatter object to send the output to.
323
if not isinstance(lf, LogFormatter):
324
warn("not a LogFormatter instance: %r" % lf)
326
self.branch.lock_read()
328
if getattr(lf, 'begin_log', None):
331
if getattr(lf, 'end_log', None):
336
def _show_body(self, lf):
337
"""Show the main log output.
339
Subclasses may wish to override this.
341
# Tweak the LogRequest based on what the LogFormatter can handle.
342
# (There's no point generating stuff if the formatter can't display it.)
344
rqst['levels'] = lf.get_levels()
345
if not getattr(lf, 'supports_tags', False):
346
rqst['generate_tags'] = False
347
if not getattr(lf, 'supports_delta', False):
348
rqst['delta_type'] = None
349
if not getattr(lf, 'supports_diff', False):
350
rqst['diff_type'] = None
351
if not getattr(lf, 'supports_merge_revisions', False):
352
rqst['_allow_single_merge_revision'] = getattr(lf,
353
'supports_single_merge_revision', False)
355
# Find and print the interesting revisions
356
generator = self._generator_factory(self.branch, rqst)
357
for lr in generator.iter_log_revisions():
360
def _generator_factory(self, branch, rqst):
361
"""Make the LogGenerator object to use.
363
Subclasses may wish to override this.
365
return _DefaultLogGenerator(branch, rqst)
368
class _StartNotLinearAncestor(Exception):
369
"""Raised when a start revision is not found walking left-hand history."""
372
class _DefaultLogGenerator(LogGenerator):
373
"""The default generator of log revisions."""
375
def __init__(self, branch, rqst):
378
if rqst.get('generate_tags') and branch.supports_tags():
379
self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
381
self.rev_tag_dict = {}
383
def iter_log_revisions(self):
384
"""Iterate over LogRevision objects.
386
:return: An iterator yielding LogRevision objects.
390
revision_iterator = self._create_log_revision_iterator()
391
for revs in revision_iterator:
392
for (rev_id, revno, merge_depth), rev, delta in revs:
393
# 0 levels means show everything; merge_depth counts from 0
394
levels = rqst.get('levels')
395
if levels != 0 and merge_depth >= levels:
397
diff = self._format_diff(rev, rev_id)
398
yield LogRevision(rev, revno, merge_depth, delta,
399
self.rev_tag_dict.get(rev_id), diff)
400
limit = rqst.get('limit')
403
if log_count >= limit:
406
def _format_diff(self, rev, rev_id):
407
diff_type = self.rqst.get('diff_type')
408
if diff_type is None:
410
repo = self.branch.repository
411
if len(rev.parent_ids) == 0:
412
ancestor_id = _mod_revision.NULL_REVISION
414
ancestor_id = rev.parent_ids[0]
415
tree_1 = repo.revision_tree(ancestor_id)
416
tree_2 = repo.revision_tree(rev_id)
417
file_ids = self.rqst.get('specific_fileids')
418
if diff_type == 'partial' and file_ids is not None:
419
specific_files = [tree_2.id2path(id) for id in file_ids]
421
specific_files = None
423
diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
427
def _create_log_revision_iterator(self):
428
"""Create a revision iterator for log.
430
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
433
self.start_rev_id, self.end_rev_id = _get_revision_limits(
434
self.branch, self.rqst.get('start_revision'),
435
self.rqst.get('end_revision'))
436
if self.rqst.get('_match_using_deltas'):
437
return self._log_revision_iterator_using_delta_matching()
439
# We're using the per-file-graph algorithm. This scales really
440
# well but only makes sense if there is a single file and it's
442
file_count = len(self.rqst.get('specific_fileids'))
444
raise BzrError("illegal LogRequest: must match-using-deltas "
445
"when logging %d files" % file_count)
446
return self._log_revision_iterator_using_per_file_graph()
448
def _log_revision_iterator_using_delta_matching(self):
449
# Get the base revisions, filtering by the revision range
451
generate_merge_revisions = rqst.get('levels') != 1
452
delayed_graph_generation = not rqst.get('specific_fileids') and (
453
rqst.get('limit') or self.start_rev_id or self.end_rev_id)
454
view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
455
self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
456
rqst.get('_allow_single_merge_revision'),
457
delayed_graph_generation=delayed_graph_generation)
459
# Apply the other filters
460
return make_log_rev_iterator(self.branch, view_revisions,
461
rqst.get('delta_type'), rqst.get('message_search'),
462
file_ids=rqst.get('specific_fileids'),
463
direction=rqst.get('direction'))
465
def _log_revision_iterator_using_per_file_graph(self):
466
# Get the base revisions, filtering by the revision range.
467
# Note that we always generate the merge revisions because
468
# filter_revisions_touching_file_id() requires them ...
470
view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
471
self.end_rev_id, rqst.get('direction'), True,
472
rqst.get('_allow_single_merge_revision'))
473
if not isinstance(view_revisions, list):
474
view_revisions = list(view_revisions)
475
view_revisions = _filter_revisions_touching_file_id(self.branch,
476
rqst.get('specific_fileids')[0], view_revisions,
477
include_merges=rqst.get('levels') != 1)
478
return make_log_rev_iterator(self.branch, view_revisions,
479
rqst.get('delta_type'), rqst.get('message_search'))
482
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
483
generate_merge_revisions, allow_single_merge_revision,
484
delayed_graph_generation=False):
485
"""Calculate the revisions to view.
487
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
488
a list of the same tuples.
490
br_revno, br_rev_id = branch.last_revision_info()
494
# If a single revision is requested, check we can handle it
495
generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
496
(not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
497
if generate_single_revision:
498
return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno,
499
allow_single_merge_revision)
501
# If we only want to see linear revisions, we can iterate ...
502
if not generate_merge_revisions:
503
return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
506
return _generate_all_revisions(branch, start_rev_id, end_rev_id,
507
direction, delayed_graph_generation)
510
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno,
511
allow_single_merge_revision):
512
if rev_id == br_rev_id:
514
return [(br_rev_id, br_revno, 0)]
516
revno = branch.revision_id_to_dotted_revno(rev_id)
517
if len(revno) > 1 and not allow_single_merge_revision:
518
# It's a merge revision and the log formatter is
519
# completely brain dead. This "feature" of allowing
520
# log formatters incapable of displaying dotted revnos
521
# ought to be deprecated IMNSHO. IGC 20091022
522
raise errors.BzrCommandError('Selected log formatter only'
523
' supports mainline revisions.')
524
revno_str = '.'.join(str(n) for n in revno)
525
return [(rev_id, revno_str, 0)]
528
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
529
result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
530
# If a start limit was given and it's not obviously an
531
# ancestor of the end limit, check it before outputting anything
532
if direction == 'forward' or (start_rev_id
533
and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
535
result = list(result)
536
except _StartNotLinearAncestor:
537
raise errors.BzrCommandError('Start revision not found in'
538
' left-hand history of end revision.')
539
if direction == 'forward':
540
result = reversed(result)
544
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
545
delayed_graph_generation):
546
# On large trees, generating the merge graph can take 30-60 seconds
547
# so we delay doing it until a merge is detected, incrementally
548
# returning initial (non-merge) revisions while we can.
549
initial_revisions = []
550
if delayed_graph_generation:
552
for rev_id, revno, depth in \
553
_linear_view_revisions(branch, start_rev_id, end_rev_id):
554
if _has_merges(branch, rev_id):
558
initial_revisions.append((rev_id, revno, depth))
560
# No merged revisions found
561
if direction == 'reverse':
562
return initial_revisions
563
elif direction == 'forward':
564
return reversed(initial_revisions)
566
raise ValueError('invalid direction %r' % direction)
567
except _StartNotLinearAncestor:
568
# A merge was never detected so the lower revision limit can't
569
# be nested down somewhere
570
raise errors.BzrCommandError('Start revision not found in'
571
' history of end revision.')
573
# A log including nested merges is required. If the direction is reverse,
574
# we rebase the initial merge depths so that the development line is
575
# shown naturally, i.e. just like it is for linear logging. We can easily
576
# make forward the exact opposite display, but showing the merge revisions
577
# indented at the end seems slightly nicer in that case.
578
view_revisions = chain(iter(initial_revisions),
579
_graph_view_revisions(branch, start_rev_id, end_rev_id,
580
rebase_initial_depths=direction == 'reverse'))
581
if direction == 'reverse':
582
return view_revisions
583
elif direction == 'forward':
584
# Forward means oldest first, adjusting for depth.
585
view_revisions = reverse_by_depth(list(view_revisions))
586
return _rebase_merge_depth(view_revisions)
588
raise ValueError('invalid direction %r' % direction)
591
def _has_merges(branch, rev_id):
592
"""Does a revision have multiple parents or not?"""
593
parents = branch.repository.get_parent_map([rev_id]).get(rev_id, [])
594
return len(parents) > 1
597
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
598
"""Is start_rev_id an obvious ancestor of end_rev_id?"""
599
if start_rev_id and end_rev_id:
600
start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
601
end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
602
if len(start_dotted) == 1 and len(end_dotted) == 1:
604
return start_dotted[0] <= end_dotted[0]
605
elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
606
start_dotted[0:1] == end_dotted[0:1]):
607
# both on same development line
608
return start_dotted[2] <= end_dotted[2]
615
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
616
"""Calculate a sequence of revisions to view, newest to oldest.
618
:param start_rev_id: the lower revision-id
619
:param end_rev_id: the upper revision-id
620
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
621
:raises _StartNotLinearAncestor: if a start_rev_id is specified but
622
is not found walking the left-hand history
624
br_revno, br_rev_id = branch.last_revision_info()
625
repo = branch.repository
626
if start_rev_id is None and end_rev_id is None:
628
for revision_id in repo.iter_reverse_revision_history(br_rev_id):
629
yield revision_id, str(cur_revno), 0
632
if end_rev_id is None:
633
end_rev_id = br_rev_id
634
found_start = start_rev_id is None
635
for revision_id in repo.iter_reverse_revision_history(end_rev_id):
636
revno = branch.revision_id_to_dotted_revno(revision_id)
637
revno_str = '.'.join(str(n) for n in revno)
638
if not found_start and revision_id == start_rev_id:
639
yield revision_id, revno_str, 0
643
yield revision_id, revno_str, 0
646
raise _StartNotLinearAncestor()
649
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
650
rebase_initial_depths=True):
651
"""Calculate revisions to view including merges, newest to oldest.
653
:param branch: the branch
654
:param start_rev_id: the lower revision-id
655
:param end_rev_id: the upper revision-id
656
:param rebase_initial_depth: should depths be rebased until a mainline
658
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
660
view_revisions = branch.iter_merge_sorted_revisions(
661
start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
662
stop_rule="with-merges")
663
if not rebase_initial_depths:
664
for (rev_id, merge_depth, revno, end_of_merge
666
yield rev_id, '.'.join(map(str, revno)), merge_depth
668
# We're following a development line starting at a merged revision.
669
# We need to adjust depths down by the initial depth until we find
670
# a depth less than it. Then we use that depth as the adjustment.
671
# If and when we reach the mainline, depth adjustment ends.
672
depth_adjustment = None
673
for (rev_id, merge_depth, revno, end_of_merge
675
if depth_adjustment is None:
676
depth_adjustment = merge_depth
678
if merge_depth < depth_adjustment:
679
depth_adjustment = merge_depth
680
merge_depth -= depth_adjustment
681
yield rev_id, '.'.join(map(str, revno)), merge_depth
684
def calculate_view_revisions(branch, start_revision, end_revision, direction,
685
specific_fileid, generate_merge_revisions, allow_single_merge_revision):
686
"""Calculate the revisions to view.
688
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
689
a list of the same tuples.
691
# This method is no longer called by the main code path.
692
# It is retained for API compatibility and may be deprecated
694
start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
696
view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
697
direction, generate_merge_revisions or specific_fileid,
698
allow_single_merge_revision))
700
view_revisions = _filter_revisions_touching_file_id(branch,
701
specific_fileid, view_revisions,
702
include_merges=generate_merge_revisions)
703
return _rebase_merge_depth(view_revisions)
706
def _rebase_merge_depth(view_revisions):
707
"""Adjust depths upwards so the top level is 0."""
708
# If either the first or last revision have a merge_depth of 0, we're done
709
if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
710
min_depth = min([d for r,n,d in view_revisions])
712
view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
713
return view_revisions
716
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
717
file_ids=None, direction='reverse'):
718
"""Create a revision iterator for log.
720
:param branch: The branch being logged.
721
:param view_revisions: The revisions being viewed.
722
:param generate_delta: Whether to generate a delta for each revision.
723
Permitted values are None, 'full' and 'partial'.
724
:param search: A user text search string.
725
:param file_ids: If non empty, only revisions matching one or more of
726
the file-ids are to be kept.
727
:param direction: the direction in which view_revisions is sorted
728
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
731
# Convert view_revisions into (view, None, None) groups to fit with
732
# the standard interface here.
733
if type(view_revisions) == list:
734
# A single batch conversion is faster than many incremental ones.
735
# As we have all the data, do a batch conversion.
736
nones = [None] * len(view_revisions)
737
log_rev_iterator = iter([zip(view_revisions, nones, nones)])
740
for view in view_revisions:
741
yield (view, None, None)
742
log_rev_iterator = iter([_convert()])
743
for adapter in log_adapters:
744
# It would be nicer if log adapters were first class objects
745
# with custom parameters. This will do for now. IGC 20090127
746
if adapter == _make_delta_filter:
747
log_rev_iterator = adapter(branch, generate_delta,
748
search, log_rev_iterator, file_ids, direction)
750
log_rev_iterator = adapter(branch, generate_delta,
751
search, log_rev_iterator)
752
return log_rev_iterator
755
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
756
"""Create a filtered iterator of log_rev_iterator matching on a regex.
758
:param branch: The branch being logged.
759
:param generate_delta: Whether to generate a delta for each revision.
760
:param search: A user text search string.
761
:param log_rev_iterator: An input iterator containing all revisions that
762
could be displayed, in lists.
763
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
767
return log_rev_iterator
768
searchRE = re_compile_checked(search, re.IGNORECASE,
769
'log message filter')
770
return _filter_message_re(searchRE, log_rev_iterator)
773
def _filter_message_re(searchRE, log_rev_iterator):
774
for revs in log_rev_iterator:
776
for (rev_id, revno, merge_depth), rev, delta in revs:
777
if searchRE.search(rev.message):
778
new_revs.append(((rev_id, revno, merge_depth), rev, delta))
782
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
783
fileids=None, direction='reverse'):
784
"""Add revision deltas to a log iterator if needed.
786
:param branch: The branch being logged.
787
:param generate_delta: Whether to generate a delta for each revision.
788
Permitted values are None, 'full' and 'partial'.
789
:param search: A user text search string.
790
:param log_rev_iterator: An input iterator containing all revisions that
791
could be displayed, in lists.
792
:param fileids: If non empty, only revisions matching one or more of
793
the file-ids are to be kept.
794
:param direction: the direction in which view_revisions is sorted
795
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
798
if not generate_delta and not fileids:
799
return log_rev_iterator
800
return _generate_deltas(branch.repository, log_rev_iterator,
801
generate_delta, fileids, direction)
804
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
806
"""Create deltas for each batch of revisions in log_rev_iterator.
808
If we're only generating deltas for the sake of filtering against
809
file-ids, we stop generating deltas once all file-ids reach the
810
appropriate life-cycle point. If we're receiving data newest to
811
oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
813
check_fileids = fileids is not None and len(fileids) > 0
815
fileid_set = set(fileids)
816
if direction == 'reverse':
822
for revs in log_rev_iterator:
823
# If we were matching against fileids and we've run out,
824
# there's nothing left to do
825
if check_fileids and not fileid_set:
827
revisions = [rev[1] for rev in revs]
829
if delta_type == 'full' and not check_fileids:
830
deltas = repository.get_deltas_for_revisions(revisions)
831
for rev, delta in izip(revs, deltas):
832
new_revs.append((rev[0], rev[1], delta))
834
deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
835
for rev, delta in izip(revs, deltas):
837
if delta is None or not delta.has_changed():
840
_update_fileids(delta, fileid_set, stop_on)
841
if delta_type is None:
843
elif delta_type == 'full':
844
# If the file matches all the time, rebuilding
845
# a full delta like this in addition to a partial
846
# one could be slow. However, it's likely that
847
# most revisions won't get this far, making it
848
# faster to filter on the partial deltas and
849
# build the occasional full delta than always
850
# building full deltas and filtering those.
852
delta = repository.get_revision_delta(rev_id)
853
new_revs.append((rev[0], rev[1], delta))
857
def _update_fileids(delta, fileids, stop_on):
858
"""Update the set of file-ids to search based on file lifecycle events.
860
:param fileids: a set of fileids to update
861
:param stop_on: either 'add' or 'remove' - take file-ids out of the
862
fileids set once their add or remove entry is detected respectively
865
for item in delta.added:
866
if item[1] in fileids:
867
fileids.remove(item[1])
868
elif stop_on == 'delete':
869
for item in delta.removed:
870
if item[1] in fileids:
871
fileids.remove(item[1])
874
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
875
"""Extract revision objects from the repository
877
:param branch: The branch being logged.
878
:param generate_delta: Whether to generate a delta for each revision.
879
:param search: A user text search string.
880
:param log_rev_iterator: An input iterator containing all revisions that
881
could be displayed, in lists.
882
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
885
repository = branch.repository
886
for revs in log_rev_iterator:
887
# r = revision_id, n = revno, d = merge depth
888
revision_ids = [view[0] for view, _, _ in revs]
889
revisions = repository.get_revisions(revision_ids)
890
revs = [(rev[0], revision, rev[2]) for rev, revision in
891
izip(revs, revisions)]
895
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
896
"""Group up a single large batch into smaller ones.
898
:param branch: The branch being logged.
899
:param generate_delta: Whether to generate a delta for each revision.
900
:param search: A user text search string.
901
:param log_rev_iterator: An input iterator containing all revisions that
902
could be displayed, in lists.
903
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
906
repository = branch.repository
908
for batch in log_rev_iterator:
911
step = [detail for _, detail in zip(range(num), batch)]
915
num = min(int(num * 1.5), 200)
918
def _get_revision_limits(branch, start_revision, end_revision):
919
"""Get and check revision limits.
921
:param branch: The branch containing the revisions.
923
:param start_revision: The first revision to be logged.
924
For backwards compatibility this may be a mainline integer revno,
925
but for merge revision support a RevisionInfo is expected.
927
:param end_revision: The last revision to be logged.
928
For backwards compatibility this may be a mainline integer revno,
929
but for merge revision support a RevisionInfo is expected.
931
:return: (start_rev_id, end_rev_id) tuple.
933
branch_revno, branch_rev_id = branch.last_revision_info()
935
if start_revision is None:
938
if isinstance(start_revision, revisionspec.RevisionInfo):
939
start_rev_id = start_revision.rev_id
940
start_revno = start_revision.revno or 1
942
branch.check_real_revno(start_revision)
943
start_revno = start_revision
944
start_rev_id = branch.get_rev_id(start_revno)
947
if end_revision is None:
948
end_revno = branch_revno
950
if isinstance(end_revision, revisionspec.RevisionInfo):
951
end_rev_id = end_revision.rev_id
952
end_revno = end_revision.revno or branch_revno
954
branch.check_real_revno(end_revision)
955
end_revno = end_revision
956
end_rev_id = branch.get_rev_id(end_revno)
958
if branch_revno != 0:
959
if (start_rev_id == _mod_revision.NULL_REVISION
960
or end_rev_id == _mod_revision.NULL_REVISION):
961
raise errors.BzrCommandError('Logging revision 0 is invalid.')
962
if start_revno > end_revno:
963
raise errors.BzrCommandError("Start revision must be older than "
965
return (start_rev_id, end_rev_id)
968
def _get_mainline_revs(branch, start_revision, end_revision):
969
"""Get the mainline revisions from the branch.
971
Generates the list of mainline revisions for the branch.
973
:param branch: The branch containing the revisions.
975
:param start_revision: The first revision to be logged.
976
For backwards compatibility this may be a mainline integer revno,
977
but for merge revision support a RevisionInfo is expected.
979
:param end_revision: The last revision to be logged.
980
For backwards compatibility this may be a mainline integer revno,
981
but for merge revision support a RevisionInfo is expected.
983
:return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
985
branch_revno, branch_last_revision = branch.last_revision_info()
986
if branch_revno == 0:
987
return None, None, None, None
989
# For mainline generation, map start_revision and end_revision to
990
# mainline revnos. If the revision is not on the mainline choose the
991
# appropriate extreme of the mainline instead - the extra will be
993
# Also map the revisions to rev_ids, to be used in the later filtering
996
if start_revision is None:
999
if isinstance(start_revision, revisionspec.RevisionInfo):
1000
start_rev_id = start_revision.rev_id
1001
start_revno = start_revision.revno or 1
1003
branch.check_real_revno(start_revision)
1004
start_revno = start_revision
1007
if end_revision is None:
1008
end_revno = branch_revno
1010
if isinstance(end_revision, revisionspec.RevisionInfo):
1011
end_rev_id = end_revision.rev_id
1012
end_revno = end_revision.revno or branch_revno
1014
branch.check_real_revno(end_revision)
1015
end_revno = end_revision
1017
if ((start_rev_id == _mod_revision.NULL_REVISION)
1018
or (end_rev_id == _mod_revision.NULL_REVISION)):
1019
raise errors.BzrCommandError('Logging revision 0 is invalid.')
1020
if start_revno > end_revno:
1021
raise errors.BzrCommandError("Start revision must be older than "
1022
"the end revision.")
1024
if end_revno < start_revno:
1025
return None, None, None, None
1026
cur_revno = branch_revno
1029
for revision_id in branch.repository.iter_reverse_revision_history(
1030
branch_last_revision):
1031
if cur_revno < start_revno:
1032
# We have gone far enough, but we always add 1 more revision
1033
rev_nos[revision_id] = cur_revno
1034
mainline_revs.append(revision_id)
1036
if cur_revno <= end_revno:
1037
rev_nos[revision_id] = cur_revno
1038
mainline_revs.append(revision_id)
1041
# We walked off the edge of all revisions, so we add a 'None' marker
1042
mainline_revs.append(None)
1044
mainline_revs.reverse()
1046
# override the mainline to look like the revision history.
1047
return mainline_revs, rev_nos, start_rev_id, end_rev_id
1050
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1051
"""Filter view_revisions based on revision ranges.
1053
:param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
1054
tuples to be filtered.
1056
:param start_rev_id: If not NONE specifies the first revision to be logged.
1057
If NONE then all revisions up to the end_rev_id are logged.
1059
:param end_rev_id: If not NONE specifies the last revision to be logged.
1060
If NONE then all revisions up to the end of the log are logged.
1062
:return: The filtered view_revisions.
1064
# This method is no longer called by the main code path.
1065
# It may be removed soon. IGC 20090127
1066
if start_rev_id or end_rev_id:
1067
revision_ids = [r for r, n, d in view_revisions]
1069
start_index = revision_ids.index(start_rev_id)
1072
if start_rev_id == end_rev_id:
1073
end_index = start_index
1076
end_index = revision_ids.index(end_rev_id)
1078
end_index = len(view_revisions) - 1
1079
# To include the revisions merged into the last revision,
1080
# extend end_rev_id down to, but not including, the next rev
1081
# with the same or lesser merge_depth
1082
end_merge_depth = view_revisions[end_index][2]
1084
for index in xrange(end_index+1, len(view_revisions)+1):
1085
if view_revisions[index][2] <= end_merge_depth:
1086
end_index = index - 1
1089
# if the search falls off the end then log to the end as well
1090
end_index = len(view_revisions) - 1
1091
view_revisions = view_revisions[start_index:end_index+1]
1092
return view_revisions
1095
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
1096
include_merges=True):
1097
r"""Return the list of revision ids which touch a given file id.
1099
The function filters view_revisions and returns a subset.
1100
This includes the revisions which directly change the file id,
1101
and the revisions which merge these changes. So if the
1113
And 'C' changes a file, then both C and D will be returned. F will not be
1114
returned even though it brings the changes to C into the branch starting
1115
with E. (Note that if we were using F as the tip instead of G, then we
1118
This will also be restricted based on a subset of the mainline.
1120
:param branch: The branch where we can get text revision information.
1122
:param file_id: Filter out revisions that do not touch file_id.
1124
:param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
1125
tuples. This is the list of revisions which will be filtered. It is
1126
assumed that view_revisions is in merge_sort order (i.e. newest
1129
:param include_merges: include merge revisions in the result or not
1131
:return: A list of (revision_id, dotted_revno, merge_depth) tuples.
1133
# Lookup all possible text keys to determine which ones actually modified
1135
text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
1137
# Looking up keys in batches of 1000 can cut the time in half, as well as
1138
# memory consumption. GraphIndex *does* like to look for a few keys in
1139
# parallel, it just doesn't like looking for *lots* of keys in parallel.
1140
# TODO: This code needs to be re-evaluated periodically as we tune the
1141
# indexing layer. We might consider passing in hints as to the known
1142
# access pattern (sparse/clustered, high success rate/low success
1143
# rate). This particular access is clustered with a low success rate.
1144
get_parent_map = branch.repository.texts.get_parent_map
1145
modified_text_revisions = set()
1147
for start in xrange(0, len(text_keys), chunk_size):
1148
next_keys = text_keys[start:start + chunk_size]
1149
# Only keep the revision_id portion of the key
1150
modified_text_revisions.update(
1151
[k[1] for k in get_parent_map(next_keys)])
1152
del text_keys, next_keys
1155
# Track what revisions will merge the current revision, replace entries
1156
# with 'None' when they have been added to result
1157
current_merge_stack = [None]
1158
for info in view_revisions:
1159
rev_id, revno, depth = info
1160
if depth == len(current_merge_stack):
1161
current_merge_stack.append(info)
1163
del current_merge_stack[depth + 1:]
1164
current_merge_stack[-1] = info
1166
if rev_id in modified_text_revisions:
1167
# This needs to be logged, along with the extra revisions
1168
for idx in xrange(len(current_merge_stack)):
1169
node = current_merge_stack[idx]
1170
if node is not None:
1171
if include_merges or node[2] == 0:
1173
current_merge_stack[idx] = None
1177
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1178
include_merges=True):
1179
"""Produce an iterator of revisions to show
1180
:return: an iterator of (revision_id, revno, merge_depth)
1181
(if there is no revno for a revision, None is supplied)
1183
# This method is no longer called by the main code path.
1184
# It is retained for API compatibility and may be deprecated
1185
# soon. IGC 20090127
1186
if not include_merges:
1187
revision_ids = mainline_revs[1:]
1188
if direction == 'reverse':
1189
revision_ids.reverse()
1190
for revision_id in revision_ids:
1191
yield revision_id, str(rev_nos[revision_id]), 0
1193
graph = branch.repository.get_graph()
1194
# This asks for all mainline revisions, which means we only have to spider
1195
# sideways, rather than depth history. That said, its still size-of-history
1196
# and should be addressed.
1197
# mainline_revisions always includes an extra revision at the beginning, so
1199
parent_map = dict(((key, value) for key, value in
1200
graph.iter_ancestry(mainline_revs[1:]) if value is not None))
1201
# filter out ghosts; merge_sort errors on ghosts.
1202
rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
1203
merge_sorted_revisions = tsort.merge_sort(
1207
generate_revno=True)
1209
if direction == 'forward':
1210
# forward means oldest first.
1211
merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1212
elif direction != 'reverse':
1213
raise ValueError('invalid direction %r' % direction)
1215
for (sequence, rev_id, merge_depth, revno, end_of_merge
1216
) in merge_sorted_revisions:
1217
yield rev_id, '.'.join(map(str, revno)), merge_depth
1220
def reverse_by_depth(merge_sorted_revisions, _depth=0):
1221
"""Reverse revisions by depth.
1223
Revisions with a different depth are sorted as a group with the previous
1224
revision of that depth. There may be no topological justification for this,
1225
but it looks much nicer.
1227
# Add a fake revision at start so that we can always attach sub revisions
1228
merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1230
for val in merge_sorted_revisions:
1231
if val[2] == _depth:
1232
# Each revision at the current depth becomes a chunk grouping all
1233
# higher depth revisions.
1234
zd_revisions.append([val])
1236
zd_revisions[-1].append(val)
1237
for revisions in zd_revisions:
1238
if len(revisions) > 1:
1239
# We have higher depth revisions, let reverse them locally
1240
revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1241
zd_revisions.reverse()
1243
for chunk in zd_revisions:
1244
result.extend(chunk)
1246
# Top level call, get rid of the fake revisions that have been added
1247
result = [r for r in result if r[0] is not None and r[1] is not None]
1251
class LogRevision(object):
1252
"""A revision to be logged (by LogFormatter.log_revision).
1254
A simple wrapper for the attributes of a revision to be logged.
1255
The attributes may or may not be populated, as determined by the
1256
logging options and the log formatter capabilities.
1259
def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1260
tags=None, diff=None):
1262
self.revno = str(revno)
1263
self.merge_depth = merge_depth
1269
class LogFormatter(object):
1270
"""Abstract class to display log messages.
1272
At a minimum, a derived class must implement the log_revision method.
1274
If the LogFormatter needs to be informed of the beginning or end of
1275
a log it should implement the begin_log and/or end_log hook methods.
1277
A LogFormatter should define the following supports_XXX flags
1278
to indicate which LogRevision attributes it supports:
1280
- supports_delta must be True if this log formatter supports delta.
1281
Otherwise the delta attribute may not be populated. The 'delta_format'
1282
attribute describes whether the 'short_status' format (1) or the long
1283
one (2) should be used.
1285
- supports_merge_revisions must be True if this log formatter supports
1286
merge revisions. If not, and if supports_single_merge_revision is
1287
also not True, then only mainline revisions will be passed to the
1290
- preferred_levels is the number of levels this formatter defaults to.
1291
The default value is zero meaning display all levels.
1292
This value is only relevant if supports_merge_revisions is True.
1294
- supports_single_merge_revision must be True if this log formatter
1295
supports logging only a single merge revision. This flag is
1296
only relevant if supports_merge_revisions is not True.
1298
- supports_tags must be True if this log formatter supports tags.
1299
Otherwise the tags attribute may not be populated.
1301
- supports_diff must be True if this log formatter supports diffs.
1302
Otherwise the diff attribute may not be populated.
1304
Plugins can register functions to show custom revision properties using
1305
the properties_handler_registry. The registered function
1306
must respect the following interface description:
1307
def my_show_properties(properties_dict):
1308
# code that returns a dict {'name':'value'} of the properties
1311
preferred_levels = 0
1313
def __init__(self, to_file, show_ids=False, show_timezone='original',
1314
delta_format=None, levels=None):
1315
"""Create a LogFormatter.
1317
:param to_file: the file to output to
1318
:param show_ids: if True, revision-ids are to be displayed
1319
:param show_timezone: the timezone to use
1320
:param delta_format: the level of delta information to display
1321
or None to leave it u to the formatter to decide
1322
:param levels: the number of levels to display; None or -1 to
1323
let the log formatter decide.
1325
self.to_file = to_file
1326
# 'exact' stream used to show diff, it should print content 'as is'
1327
# and should not try to decode/encode it to unicode to avoid bug #328007
1328
self.to_exact_file = getattr(to_file, 'stream', to_file)
1329
self.show_ids = show_ids
1330
self.show_timezone = show_timezone
1331
if delta_format is None:
1332
# Ensures backward compatibility
1333
delta_format = 2 # long format
1334
self.delta_format = delta_format
1335
self.levels = levels
1337
def get_levels(self):
1338
"""Get the number of levels to display or 0 for all."""
1339
if getattr(self, 'supports_merge_revisions', False):
1340
if self.levels is None or self.levels == -1:
1341
return self.preferred_levels
1346
def log_revision(self, revision):
1349
:param revision: The LogRevision to be logged.
1351
raise NotImplementedError('not implemented in abstract base')
1353
def short_committer(self, rev):
1354
name, address = config.parse_username(rev.committer)
1359
def short_author(self, rev):
1360
name, address = config.parse_username(rev.get_apparent_authors()[0])
1365
def show_properties(self, revision, indent):
1366
"""Displays the custom properties returned by each registered handler.
1368
If a registered handler raises an error it is propagated.
1370
for key, handler in properties_handler_registry.iteritems():
1371
for key, value in handler(revision).items():
1372
self.to_file.write(indent + key + ': ' + value + '\n')
1374
def show_diff(self, to_file, diff, indent):
1375
for l in diff.rstrip().split('\n'):
1376
to_file.write(indent + '%s\n' % (l,))
1379
class LongLogFormatter(LogFormatter):
1381
supports_merge_revisions = True
1382
preferred_levels = 1
1383
supports_delta = True
1384
supports_tags = True
1385
supports_diff = True
1387
def log_revision(self, revision):
1388
"""Log a revision, either merged or not."""
1389
indent = ' ' * revision.merge_depth
1390
to_file = self.to_file
1391
to_file.write(indent + '-' * 60 + '\n')
1392
if revision.revno is not None:
1393
to_file.write(indent + 'revno: %s\n' % (revision.revno,))
1395
to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1397
to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1399
for parent_id in revision.rev.parent_ids:
1400
to_file.write(indent + 'parent: %s\n' % (parent_id,))
1401
self.show_properties(revision.rev, indent)
1403
committer = revision.rev.committer
1404
authors = revision.rev.get_apparent_authors()
1405
if authors != [committer]:
1406
to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1407
to_file.write(indent + 'committer: %s\n' % (committer,))
1409
branch_nick = revision.rev.properties.get('branch-nick', None)
1410
if branch_nick is not None:
1411
to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
1413
date_str = format_date(revision.rev.timestamp,
1414
revision.rev.timezone or 0,
1416
to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1418
to_file.write(indent + 'message:\n')
1419
if not revision.rev.message:
1420
to_file.write(indent + ' (no message)\n')
1422
message = revision.rev.message.rstrip('\r\n')
1423
for l in message.split('\n'):
1424
to_file.write(indent + ' %s\n' % (l,))
1425
if revision.delta is not None:
1426
# We don't respect delta_format for compatibility
1427
revision.delta.show(to_file, self.show_ids, indent=indent,
1429
if revision.diff is not None:
1430
to_file.write(indent + 'diff:\n')
1431
# Note: we explicitly don't indent the diff (relative to the
1432
# revision information) so that the output can be fed to patch -p0
1433
self.show_diff(self.to_exact_file, revision.diff, indent)
1436
class ShortLogFormatter(LogFormatter):
1438
supports_merge_revisions = True
1439
preferred_levels = 1
1440
supports_delta = True
1441
supports_tags = True
1442
supports_diff = True
1444
def __init__(self, *args, **kwargs):
1445
super(ShortLogFormatter, self).__init__(*args, **kwargs)
1446
self.revno_width_by_depth = {}
1448
def log_revision(self, revision):
1449
# We need two indents: one per depth and one for the information
1450
# relative to that indent. Most mainline revnos are 5 chars or
1451
# less while dotted revnos are typically 11 chars or less. Once
1452
# calculated, we need to remember the offset for a given depth
1453
# as we might be starting from a dotted revno in the first column
1454
# and we want subsequent mainline revisions to line up.
1455
depth = revision.merge_depth
1456
indent = ' ' * depth
1457
revno_width = self.revno_width_by_depth.get(depth)
1458
if revno_width is None:
1459
if revision.revno.find('.') == -1:
1460
# mainline revno, e.g. 12345
1463
# dotted revno, e.g. 12345.10.55
1465
self.revno_width_by_depth[depth] = revno_width
1466
offset = ' ' * (revno_width + 1)
1468
to_file = self.to_file
1470
if len(revision.rev.parent_ids) > 1:
1471
is_merge = ' [merge]'
1474
tags = ' {%s}' % (', '.join(revision.tags))
1475
to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1476
revision.revno, self.short_author(revision.rev),
1477
format_date(revision.rev.timestamp,
1478
revision.rev.timezone or 0,
1479
self.show_timezone, date_fmt="%Y-%m-%d",
1482
self.show_properties(revision.rev, indent+offset)
1484
to_file.write(indent + offset + 'revision-id:%s\n'
1485
% (revision.rev.revision_id,))
1486
if not revision.rev.message:
1487
to_file.write(indent + offset + '(no message)\n')
1489
message = revision.rev.message.rstrip('\r\n')
1490
for l in message.split('\n'):
1491
to_file.write(indent + offset + '%s\n' % (l,))
1493
if revision.delta is not None:
1494
revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1495
short_status=self.delta_format==1)
1496
if revision.diff is not None:
1497
self.show_diff(self.to_exact_file, revision.diff, ' ')
1501
class LineLogFormatter(LogFormatter):
1503
supports_merge_revisions = True
1504
preferred_levels = 1
1505
supports_tags = True
1507
def __init__(self, *args, **kwargs):
1508
super(LineLogFormatter, self).__init__(*args, **kwargs)
1509
self._max_chars = terminal_width() - 1
1511
def truncate(self, str, max_len):
1512
if len(str) <= max_len:
1514
return str[:max_len-3]+'...'
1516
def date_string(self, rev):
1517
return format_date(rev.timestamp, rev.timezone or 0,
1518
self.show_timezone, date_fmt="%Y-%m-%d",
1521
def message(self, rev):
1523
return '(no message)'
1527
def log_revision(self, revision):
1528
indent = ' ' * revision.merge_depth
1529
self.to_file.write(self.log_string(revision.revno, revision.rev,
1530
self._max_chars, revision.tags, indent))
1531
self.to_file.write('\n')
1533
def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1534
"""Format log info into one string. Truncate tail of string
1535
:param revno: revision number or None.
1536
Revision numbers counts from 1.
1537
:param rev: revision object
1538
:param max_chars: maximum length of resulting string
1539
:param tags: list of tags or None
1540
:param prefix: string to prefix each line
1541
:return: formatted truncated string
1545
# show revno only when is not None
1546
out.append("%s:" % revno)
1547
out.append(self.truncate(self.short_author(rev), 20))
1548
out.append(self.date_string(rev))
1549
if len(rev.parent_ids) > 1:
1550
out.append('[merge]')
1552
tag_str = '{%s}' % (', '.join(tags))
1554
out.append(rev.get_summary())
1555
return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
1558
class GnuChangelogLogFormatter(LogFormatter):
1560
supports_merge_revisions = True
1561
supports_delta = True
1563
def log_revision(self, revision):
1564
"""Log a revision, either merged or not."""
1565
to_file = self.to_file
1567
date_str = format_date(revision.rev.timestamp,
1568
revision.rev.timezone or 0,
1570
date_fmt='%Y-%m-%d',
1572
committer_str = revision.rev.committer.replace (' <', ' <')
1573
to_file.write('%s %s\n\n' % (date_str,committer_str))
1575
if revision.delta is not None and revision.delta.has_changed():
1576
for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
1578
to_file.write('\t* %s:\n' % (path,))
1579
for c in revision.delta.renamed:
1580
oldpath,newpath = c[:2]
1581
# For renamed files, show both the old and the new path
1582
to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
1585
if not revision.rev.message:
1586
to_file.write('\tNo commit message\n')
1588
message = revision.rev.message.rstrip('\r\n')
1589
for l in message.split('\n'):
1590
to_file.write('\t%s\n' % (l.lstrip(),))
1594
def line_log(rev, max_chars):
1595
lf = LineLogFormatter(None)
1596
return lf.log_string(None, rev, max_chars)
1599
class LogFormatterRegistry(registry.Registry):
1600
"""Registry for log formatters"""
1602
def make_formatter(self, name, *args, **kwargs):
1603
"""Construct a formatter from arguments.
1605
:param name: Name of the formatter to construct. 'short', 'long' and
1606
'line' are built-in.
1608
return self.get(name)(*args, **kwargs)
1610
def get_default(self, branch):
1611
return self.get(branch.get_config().log_format())
1614
log_formatter_registry = LogFormatterRegistry()
1617
log_formatter_registry.register('short', ShortLogFormatter,
1618
'Moderately short log format')
1619
log_formatter_registry.register('long', LongLogFormatter,
1620
'Detailed log format')
1621
log_formatter_registry.register('line', LineLogFormatter,
1622
'Log format with one line per revision')
1623
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
1624
'Format used by GNU ChangeLog files')
1627
def register_formatter(name, formatter):
1628
log_formatter_registry.register(name, formatter)
1631
def log_formatter(name, *args, **kwargs):
1632
"""Construct a formatter from arguments.
1634
name -- Name of the formatter to construct; currently 'long', 'short' and
1635
'line' are supported.
1638
return log_formatter_registry.make_formatter(name, *args, **kwargs)
1640
raise errors.BzrCommandError("unknown log formatter: %r" % name)
1643
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1644
# deprecated; for compatibility
1645
lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1646
lf.show(revno, rev, delta)
1649
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1651
"""Show the change in revision history comparing the old revision history to the new one.
1653
:param branch: The branch where the revisions exist
1654
:param old_rh: The old revision history
1655
:param new_rh: The new revision history
1656
:param to_file: A file to write the results to. If None, stdout will be used
1659
to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1661
lf = log_formatter(log_format,
1664
show_timezone='original')
1666
# This is the first index which is different between
1669
for i in xrange(max(len(new_rh),
1671
if (len(new_rh) <= i
1673
or new_rh[i] != old_rh[i]):
1677
if base_idx is None:
1678
to_file.write('Nothing seems to have changed\n')
1680
## TODO: It might be nice to do something like show_log
1681
## and show the merged entries. But since this is the
1682
## removed revisions, it shouldn't be as important
1683
if base_idx < len(old_rh):
1684
to_file.write('*'*60)
1685
to_file.write('\nRemoved Revisions:\n')
1686
for i in range(base_idx, len(old_rh)):
1687
rev = branch.repository.get_revision(old_rh[i])
1688
lr = LogRevision(rev, i+1, 0, None)
1690
to_file.write('*'*60)
1691
to_file.write('\n\n')
1692
if base_idx < len(new_rh):
1693
to_file.write('Added Revisions:\n')
1698
direction='forward',
1699
start_revision=base_idx+1,
1700
end_revision=len(new_rh),
1704
def get_history_change(old_revision_id, new_revision_id, repository):
1705
"""Calculate the uncommon lefthand history between two revisions.
1707
:param old_revision_id: The original revision id.
1708
:param new_revision_id: The new revision id.
1709
:param repository: The repository to use for the calculation.
1711
return old_history, new_history
1714
old_revisions = set()
1716
new_revisions = set()
1717
new_iter = repository.iter_reverse_revision_history(new_revision_id)
1718
old_iter = repository.iter_reverse_revision_history(old_revision_id)
1719
stop_revision = None
1722
while do_new or do_old:
1725
new_revision = new_iter.next()
1726
except StopIteration:
1729
new_history.append(new_revision)
1730
new_revisions.add(new_revision)
1731
if new_revision in old_revisions:
1732
stop_revision = new_revision
1736
old_revision = old_iter.next()
1737
except StopIteration:
1740
old_history.append(old_revision)
1741
old_revisions.add(old_revision)
1742
if old_revision in new_revisions:
1743
stop_revision = old_revision
1745
new_history.reverse()
1746
old_history.reverse()
1747
if stop_revision is not None:
1748
new_history = new_history[new_history.index(stop_revision) + 1:]
1749
old_history = old_history[old_history.index(stop_revision) + 1:]
1750
return old_history, new_history
1753
def show_branch_change(branch, output, old_revno, old_revision_id):
1754
"""Show the changes made to a branch.
1756
:param branch: The branch to show changes about.
1757
:param output: A file-like object to write changes to.
1758
:param old_revno: The revno of the old tip.
1759
:param old_revision_id: The revision_id of the old tip.
1761
new_revno, new_revision_id = branch.last_revision_info()
1762
old_history, new_history = get_history_change(old_revision_id,
1765
if old_history == [] and new_history == []:
1766
output.write('Nothing seems to have changed\n')
1769
log_format = log_formatter_registry.get_default(branch)
1770
lf = log_format(show_ids=False, to_file=output, show_timezone='original')
1771
if old_history != []:
1772
output.write('*'*60)
1773
output.write('\nRemoved Revisions:\n')
1774
show_flat_log(branch.repository, old_history, old_revno, lf)
1775
output.write('*'*60)
1776
output.write('\n\n')
1777
if new_history != []:
1778
output.write('Added Revisions:\n')
1779
start_revno = new_revno - len(new_history) + 1
1780
show_log(branch, lf, None, verbose=False, direction='forward',
1781
start_revision=start_revno,)
1784
def show_flat_log(repository, history, last_revno, lf):
1785
"""Show a simple log of the specified history.
1787
:param repository: The repository to retrieve revisions from.
1788
:param history: A list of revision_ids indicating the lefthand history.
1789
:param last_revno: The revno of the last revision_id in the history.
1790
:param lf: The log formatter to use.
1792
start_revno = last_revno - len(history) + 1
1793
revisions = repository.get_revisions(history)
1794
for i, rev in enumerate(revisions):
1795
lr = LogRevision(rev, i + last_revno, 0, None)
1799
def _get_info_for_log_files(revisionspec_list, file_list):
1800
"""Find file-ids and kinds given a list of files and a revision range.
1802
We search for files at the end of the range. If not found there,
1803
we try the start of the range.
1805
:param revisionspec_list: revision range as parsed on the command line
1806
:param file_list: the list of paths given on the command line;
1807
the first of these can be a branch location or a file path,
1808
the remainder must be file paths
1809
:return: (branch, info_list, start_rev_info, end_rev_info) where
1810
info_list is a list of (relative_path, file_id, kind) tuples where
1811
kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
1813
from builtins import _get_revision_range, safe_relpath_files
1814
tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
1815
# XXX: It's damn messy converting a list of paths to relative paths when
1816
# those paths might be deleted ones, they might be on a case-insensitive
1817
# filesystem and/or they might be in silly locations (like another branch).
1818
# For example, what should "log bzr://branch/dir/file1 file2" do? (Is
1819
# file2 implicitly in the same dir as file1 or should its directory be
1820
# taken from the current tree somehow?) For now, this solves the common
1821
# case of running log in a nested directory, assuming paths beyond the
1822
# first one haven't been deleted ...
1824
relpaths = [path] + safe_relpath_files(tree, file_list[1:])
1826
relpaths = [path] + file_list[1:]
1828
start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
1830
if start_rev_info is None and end_rev_info is None:
1832
tree = b.basis_tree()
1835
file_id = tree.path2id(fp)
1836
kind = _get_kind_for_file_id(tree, file_id)
1838
# go back to when time began
1841
rev1 = b.get_rev_id(1)
1842
except errors.NoSuchRevision:
1847
tree1 = b.repository.revision_tree(rev1)
1849
file_id = tree1.path2id(fp)
1850
kind = _get_kind_for_file_id(tree1, file_id)
1851
info_list.append((fp, file_id, kind))
1853
elif start_rev_info == end_rev_info:
1854
# One revision given - file must exist in it
1855
tree = b.repository.revision_tree(end_rev_info.rev_id)
1857
file_id = tree.path2id(fp)
1858
kind = _get_kind_for_file_id(tree, file_id)
1859
info_list.append((fp, file_id, kind))
1862
# Revision range given. Get the file-id from the end tree.
1863
# If that fails, try the start tree.
1864
rev_id = end_rev_info.rev_id
1866
tree = b.basis_tree()
1868
tree = b.repository.revision_tree(rev_id)
1871
file_id = tree.path2id(fp)
1872
kind = _get_kind_for_file_id(tree, file_id)
1875
rev_id = start_rev_info.rev_id
1877
rev1 = b.get_rev_id(1)
1878
tree1 = b.repository.revision_tree(rev1)
1880
tree1 = b.repository.revision_tree(rev_id)
1881
file_id = tree1.path2id(fp)
1882
kind = _get_kind_for_file_id(tree1, file_id)
1883
info_list.append((fp, file_id, kind))
1884
return b, info_list, start_rev_info, end_rev_info
1887
def _get_kind_for_file_id(tree, file_id):
1888
"""Return the kind of a file-id or None if it doesn't exist."""
1889
if file_id is not None:
1890
return tree.kind(file_id)
1895
properties_handler_registry = registry.Registry()
1896
properties_handler_registry.register_lazy("foreign",
1898
"show_foreign_properties")
1901
# adapters which revision ids to log are filtered. When log is called, the
1902
# log_rev_iterator is adapted through each of these factory methods.
1903
# Plugins are welcome to mutate this list in any way they like - as long
1904
# as the overall behaviour is preserved. At this point there is no extensible
1905
# mechanism for getting parameters to each factory method, and until there is
1906
# this won't be considered a stable api.
1910
# read revision objects
1911
_make_revision_objects,
1912
# filter on log messages
1913
_make_search_filter,
1914
# generate deltas for things we will show