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():
361
def _generator_factory(self, branch, rqst):
362
"""Make the LogGenerator object to use.
364
Subclasses may wish to override this.
366
return _DefaultLogGenerator(branch, rqst)
369
class _StartNotLinearAncestor(Exception):
370
"""Raised when a start revision is not found walking left-hand history."""
373
class _DefaultLogGenerator(LogGenerator):
374
"""The default generator of log revisions."""
376
def __init__(self, branch, rqst):
379
if rqst.get('generate_tags') and branch.supports_tags():
380
self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
382
self.rev_tag_dict = {}
384
def iter_log_revisions(self):
385
"""Iterate over LogRevision objects.
387
:return: An iterator yielding LogRevision objects.
391
revision_iterator = self._create_log_revision_iterator()
392
for revs in revision_iterator:
393
for (rev_id, revno, merge_depth), rev, delta in revs:
394
# 0 levels means show everything; merge_depth counts from 0
395
levels = rqst.get('levels')
396
if levels != 0 and merge_depth >= levels:
398
diff = self._format_diff(rev, rev_id)
399
yield LogRevision(rev, revno, merge_depth, delta,
400
self.rev_tag_dict.get(rev_id), diff)
401
limit = rqst.get('limit')
404
if log_count >= limit:
407
def _format_diff(self, rev, rev_id):
408
diff_type = self.rqst.get('diff_type')
409
if diff_type is None:
411
repo = self.branch.repository
412
if len(rev.parent_ids) == 0:
413
ancestor_id = _mod_revision.NULL_REVISION
415
ancestor_id = rev.parent_ids[0]
416
tree_1 = repo.revision_tree(ancestor_id)
417
tree_2 = repo.revision_tree(rev_id)
418
file_ids = self.rqst.get('specific_fileids')
419
if diff_type == 'partial' and file_ids is not None:
420
specific_files = [tree_2.id2path(id) for id in file_ids]
422
specific_files = None
424
diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
428
def _create_log_revision_iterator(self):
429
"""Create a revision iterator for log.
431
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
434
self.start_rev_id, self.end_rev_id = _get_revision_limits(
435
self.branch, self.rqst.get('start_revision'),
436
self.rqst.get('end_revision'))
437
if self.rqst.get('_match_using_deltas'):
438
return self._log_revision_iterator_using_delta_matching()
440
# We're using the per-file-graph algorithm. This scales really
441
# well but only makes sense if there is a single file and it's
443
file_count = len(self.rqst.get('specific_fileids'))
445
raise BzrError("illegal LogRequest: must match-using-deltas "
446
"when logging %d files" % file_count)
447
return self._log_revision_iterator_using_per_file_graph()
449
def _log_revision_iterator_using_delta_matching(self):
450
# Get the base revisions, filtering by the revision range
452
generate_merge_revisions = rqst.get('levels') != 1
453
delayed_graph_generation = not rqst.get('specific_fileids') and (
454
rqst.get('limit') or self.start_rev_id or self.end_rev_id)
455
view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
456
self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
457
rqst.get('_allow_single_merge_revision'),
458
delayed_graph_generation=delayed_graph_generation)
460
# Apply the other filters
461
return make_log_rev_iterator(self.branch, view_revisions,
462
rqst.get('delta_type'), rqst.get('message_search'),
463
file_ids=rqst.get('specific_fileids'),
464
direction=rqst.get('direction'))
466
def _log_revision_iterator_using_per_file_graph(self):
467
# Get the base revisions, filtering by the revision range.
468
# Note that we always generate the merge revisions because
469
# filter_revisions_touching_file_id() requires them ...
471
view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
472
self.end_rev_id, rqst.get('direction'), True,
473
rqst.get('_allow_single_merge_revision'))
474
if not isinstance(view_revisions, list):
475
view_revisions = list(view_revisions)
476
view_revisions = _filter_revisions_touching_file_id(self.branch,
477
rqst.get('specific_fileids')[0], view_revisions,
478
include_merges=rqst.get('levels') != 1)
479
return make_log_rev_iterator(self.branch, view_revisions,
480
rqst.get('delta_type'), rqst.get('message_search'))
483
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
484
generate_merge_revisions, allow_single_merge_revision,
485
delayed_graph_generation=False):
486
"""Calculate the revisions to view.
488
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
489
a list of the same tuples.
491
br_revno, br_rev_id = branch.last_revision_info()
495
# If a single revision is requested, check we can handle it
496
generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
497
(not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
498
if generate_single_revision:
499
return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno,
500
allow_single_merge_revision)
502
# If we only want to see linear revisions, we can iterate ...
503
if not generate_merge_revisions:
504
return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
507
return _generate_all_revisions(branch, start_rev_id, end_rev_id,
508
direction, delayed_graph_generation)
511
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno,
512
allow_single_merge_revision):
513
if rev_id == br_rev_id:
515
return [(br_rev_id, br_revno, 0)]
517
revno = branch.revision_id_to_dotted_revno(rev_id)
518
if len(revno) > 1 and not allow_single_merge_revision:
519
# It's a merge revision and the log formatter is
520
# completely brain dead. This "feature" of allowing
521
# log formatters incapable of displaying dotted revnos
522
# ought to be deprecated IMNSHO. IGC 20091022
523
raise errors.BzrCommandError('Selected log formatter only'
524
' supports mainline revisions.')
525
revno_str = '.'.join(str(n) for n in revno)
526
return [(rev_id, revno_str, 0)]
529
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
530
result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
531
# If a start limit was given and it's not obviously an
532
# ancestor of the end limit, check it before outputting anything
533
if direction == 'forward' or (start_rev_id
534
and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
536
result = list(result)
537
except _StartNotLinearAncestor:
538
raise errors.BzrCommandError('Start revision not found in'
539
' left-hand history of end revision.')
540
if direction == 'forward':
541
result = reversed(result)
545
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
546
delayed_graph_generation):
547
# On large trees, generating the merge graph can take 30-60 seconds
548
# so we delay doing it until a merge is detected, incrementally
549
# returning initial (non-merge) revisions while we can.
550
initial_revisions = []
551
if delayed_graph_generation:
553
for rev_id, revno, depth in \
554
_linear_view_revisions(branch, start_rev_id, end_rev_id):
555
if _has_merges(branch, rev_id):
559
initial_revisions.append((rev_id, revno, depth))
561
# No merged revisions found
562
if direction == 'reverse':
563
return initial_revisions
564
elif direction == 'forward':
565
return reversed(initial_revisions)
567
raise ValueError('invalid direction %r' % direction)
568
except _StartNotLinearAncestor:
569
# A merge was never detected so the lower revision limit can't
570
# be nested down somewhere
571
raise errors.BzrCommandError('Start revision not found in'
572
' history of end revision.')
574
# A log including nested merges is required. If the direction is reverse,
575
# we rebase the initial merge depths so that the development line is
576
# shown naturally, i.e. just like it is for linear logging. We can easily
577
# make forward the exact opposite display, but showing the merge revisions
578
# indented at the end seems slightly nicer in that case.
579
view_revisions = chain(iter(initial_revisions),
580
_graph_view_revisions(branch, start_rev_id, end_rev_id,
581
rebase_initial_depths=direction == 'reverse'))
582
if direction == 'reverse':
583
return view_revisions
584
elif direction == 'forward':
585
# Forward means oldest first, adjusting for depth.
586
view_revisions = reverse_by_depth(list(view_revisions))
587
return _rebase_merge_depth(view_revisions)
589
raise ValueError('invalid direction %r' % direction)
592
def _has_merges(branch, rev_id):
593
"""Does a revision have multiple parents or not?"""
594
parents = branch.repository.get_parent_map([rev_id]).get(rev_id, [])
595
return len(parents) > 1
598
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
599
"""Is start_rev_id an obvious ancestor of end_rev_id?"""
600
if start_rev_id and end_rev_id:
601
start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
602
end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
603
if len(start_dotted) == 1 and len(end_dotted) == 1:
605
return start_dotted[0] <= end_dotted[0]
606
elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
607
start_dotted[0:1] == end_dotted[0:1]):
608
# both on same development line
609
return start_dotted[2] <= end_dotted[2]
616
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
617
"""Calculate a sequence of revisions to view, newest to oldest.
619
:param start_rev_id: the lower revision-id
620
:param end_rev_id: the upper revision-id
621
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
622
:raises _StartNotLinearAncestor: if a start_rev_id is specified but
623
is not found walking the left-hand history
625
br_revno, br_rev_id = branch.last_revision_info()
626
repo = branch.repository
627
if start_rev_id is None and end_rev_id is None:
629
for revision_id in repo.iter_reverse_revision_history(br_rev_id):
630
yield revision_id, str(cur_revno), 0
633
if end_rev_id is None:
634
end_rev_id = br_rev_id
635
found_start = start_rev_id is None
636
for revision_id in repo.iter_reverse_revision_history(end_rev_id):
637
revno = branch.revision_id_to_dotted_revno(revision_id)
638
revno_str = '.'.join(str(n) for n in revno)
639
if not found_start and revision_id == start_rev_id:
640
yield revision_id, revno_str, 0
644
yield revision_id, revno_str, 0
647
raise _StartNotLinearAncestor()
650
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
651
rebase_initial_depths=True):
652
"""Calculate revisions to view including merges, newest to oldest.
654
:param branch: the branch
655
:param start_rev_id: the lower revision-id
656
:param end_rev_id: the upper revision-id
657
:param rebase_initial_depth: should depths be rebased until a mainline
659
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
661
view_revisions = branch.iter_merge_sorted_revisions(
662
start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
663
stop_rule="with-merges")
664
if not rebase_initial_depths:
665
for (rev_id, merge_depth, revno, end_of_merge
667
yield rev_id, '.'.join(map(str, revno)), merge_depth
669
# We're following a development line starting at a merged revision.
670
# We need to adjust depths down by the initial depth until we find
671
# a depth less than it. Then we use that depth as the adjustment.
672
# If and when we reach the mainline, depth adjustment ends.
673
depth_adjustment = None
674
for (rev_id, merge_depth, revno, end_of_merge
676
if depth_adjustment is None:
677
depth_adjustment = merge_depth
679
if merge_depth < depth_adjustment:
680
depth_adjustment = merge_depth
681
merge_depth -= depth_adjustment
682
yield rev_id, '.'.join(map(str, revno)), merge_depth
685
def calculate_view_revisions(branch, start_revision, end_revision, direction,
686
specific_fileid, generate_merge_revisions, allow_single_merge_revision):
687
"""Calculate the revisions to view.
689
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
690
a list of the same tuples.
692
# This method is no longer called by the main code path.
693
# It is retained for API compatibility and may be deprecated
695
start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
697
view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
698
direction, generate_merge_revisions or specific_fileid,
699
allow_single_merge_revision))
701
view_revisions = _filter_revisions_touching_file_id(branch,
702
specific_fileid, view_revisions,
703
include_merges=generate_merge_revisions)
704
return _rebase_merge_depth(view_revisions)
707
def _rebase_merge_depth(view_revisions):
708
"""Adjust depths upwards so the top level is 0."""
709
# If either the first or last revision have a merge_depth of 0, we're done
710
if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
711
min_depth = min([d for r,n,d in view_revisions])
713
view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
714
return view_revisions
717
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
718
file_ids=None, direction='reverse'):
719
"""Create a revision iterator for log.
721
:param branch: The branch being logged.
722
:param view_revisions: The revisions being viewed.
723
:param generate_delta: Whether to generate a delta for each revision.
724
Permitted values are None, 'full' and 'partial'.
725
:param search: A user text search string.
726
:param file_ids: If non empty, only revisions matching one or more of
727
the file-ids are to be kept.
728
:param direction: the direction in which view_revisions is sorted
729
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
732
# Convert view_revisions into (view, None, None) groups to fit with
733
# the standard interface here.
734
if type(view_revisions) == list:
735
# A single batch conversion is faster than many incremental ones.
736
# As we have all the data, do a batch conversion.
737
nones = [None] * len(view_revisions)
738
log_rev_iterator = iter([zip(view_revisions, nones, nones)])
741
for view in view_revisions:
742
yield (view, None, None)
743
log_rev_iterator = iter([_convert()])
744
for adapter in log_adapters:
745
# It would be nicer if log adapters were first class objects
746
# with custom parameters. This will do for now. IGC 20090127
747
if adapter == _make_delta_filter:
748
log_rev_iterator = adapter(branch, generate_delta,
749
search, log_rev_iterator, file_ids, direction)
751
log_rev_iterator = adapter(branch, generate_delta,
752
search, log_rev_iterator)
753
return log_rev_iterator
756
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
757
"""Create a filtered iterator of log_rev_iterator matching on a regex.
759
:param branch: The branch being logged.
760
:param generate_delta: Whether to generate a delta for each revision.
761
:param search: A user text search string.
762
:param log_rev_iterator: An input iterator containing all revisions that
763
could be displayed, in lists.
764
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
768
return log_rev_iterator
769
searchRE = re_compile_checked(search, re.IGNORECASE,
770
'log message filter')
771
return _filter_message_re(searchRE, log_rev_iterator)
774
def _filter_message_re(searchRE, log_rev_iterator):
775
for revs in log_rev_iterator:
777
for (rev_id, revno, merge_depth), rev, delta in revs:
778
if searchRE.search(rev.message):
779
new_revs.append(((rev_id, revno, merge_depth), rev, delta))
783
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
784
fileids=None, direction='reverse'):
785
"""Add revision deltas to a log iterator if needed.
787
:param branch: The branch being logged.
788
:param generate_delta: Whether to generate a delta for each revision.
789
Permitted values are None, 'full' and 'partial'.
790
:param search: A user text search string.
791
:param log_rev_iterator: An input iterator containing all revisions that
792
could be displayed, in lists.
793
:param fileids: If non empty, only revisions matching one or more of
794
the file-ids are to be kept.
795
:param direction: the direction in which view_revisions is sorted
796
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
799
if not generate_delta and not fileids:
800
return log_rev_iterator
801
return _generate_deltas(branch.repository, log_rev_iterator,
802
generate_delta, fileids, direction)
805
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
807
"""Create deltas for each batch of revisions in log_rev_iterator.
809
If we're only generating deltas for the sake of filtering against
810
file-ids, we stop generating deltas once all file-ids reach the
811
appropriate life-cycle point. If we're receiving data newest to
812
oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
814
check_fileids = fileids is not None and len(fileids) > 0
816
fileid_set = set(fileids)
817
if direction == 'reverse':
823
for revs in log_rev_iterator:
824
# If we were matching against fileids and we've run out,
825
# there's nothing left to do
826
if check_fileids and not fileid_set:
828
revisions = [rev[1] for rev in revs]
830
if delta_type == 'full' and not check_fileids:
831
deltas = repository.get_deltas_for_revisions(revisions)
832
for rev, delta in izip(revs, deltas):
833
new_revs.append((rev[0], rev[1], delta))
835
deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
836
for rev, delta in izip(revs, deltas):
838
if delta is None or not delta.has_changed():
841
_update_fileids(delta, fileid_set, stop_on)
842
if delta_type is None:
844
elif delta_type == 'full':
845
# If the file matches all the time, rebuilding
846
# a full delta like this in addition to a partial
847
# one could be slow. However, it's likely that
848
# most revisions won't get this far, making it
849
# faster to filter on the partial deltas and
850
# build the occasional full delta than always
851
# building full deltas and filtering those.
853
delta = repository.get_revision_delta(rev_id)
854
new_revs.append((rev[0], rev[1], delta))
858
def _update_fileids(delta, fileids, stop_on):
859
"""Update the set of file-ids to search based on file lifecycle events.
861
:param fileids: a set of fileids to update
862
:param stop_on: either 'add' or 'remove' - take file-ids out of the
863
fileids set once their add or remove entry is detected respectively
866
for item in delta.added:
867
if item[1] in fileids:
868
fileids.remove(item[1])
869
elif stop_on == 'delete':
870
for item in delta.removed:
871
if item[1] in fileids:
872
fileids.remove(item[1])
875
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
876
"""Extract revision objects from the repository
878
:param branch: The branch being logged.
879
:param generate_delta: Whether to generate a delta for each revision.
880
:param search: A user text search string.
881
:param log_rev_iterator: An input iterator containing all revisions that
882
could be displayed, in lists.
883
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
886
repository = branch.repository
887
for revs in log_rev_iterator:
888
# r = revision_id, n = revno, d = merge depth
889
revision_ids = [view[0] for view, _, _ in revs]
890
revisions = repository.get_revisions(revision_ids)
891
revs = [(rev[0], revision, rev[2]) for rev, revision in
892
izip(revs, revisions)]
896
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
897
"""Group up a single large batch into smaller ones.
899
:param branch: The branch being logged.
900
:param generate_delta: Whether to generate a delta for each revision.
901
:param search: A user text search string.
902
:param log_rev_iterator: An input iterator containing all revisions that
903
could be displayed, in lists.
904
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
907
repository = branch.repository
909
for batch in log_rev_iterator:
912
step = [detail for _, detail in zip(range(num), batch)]
916
num = min(int(num * 1.5), 200)
919
def _get_revision_limits(branch, start_revision, end_revision):
920
"""Get and check revision limits.
922
:param branch: The branch containing the revisions.
924
:param start_revision: The first revision to be logged.
925
For backwards compatibility this may be a mainline integer revno,
926
but for merge revision support a RevisionInfo is expected.
928
:param end_revision: The last revision to be logged.
929
For backwards compatibility this may be a mainline integer revno,
930
but for merge revision support a RevisionInfo is expected.
932
:return: (start_rev_id, end_rev_id) tuple.
934
branch_revno, branch_rev_id = branch.last_revision_info()
936
if start_revision is None:
939
if isinstance(start_revision, revisionspec.RevisionInfo):
940
start_rev_id = start_revision.rev_id
941
start_revno = start_revision.revno or 1
943
branch.check_real_revno(start_revision)
944
start_revno = start_revision
945
start_rev_id = branch.get_rev_id(start_revno)
948
if end_revision is None:
949
end_revno = branch_revno
951
if isinstance(end_revision, revisionspec.RevisionInfo):
952
end_rev_id = end_revision.rev_id
953
end_revno = end_revision.revno or branch_revno
955
branch.check_real_revno(end_revision)
956
end_revno = end_revision
957
end_rev_id = branch.get_rev_id(end_revno)
959
if branch_revno != 0:
960
if (start_rev_id == _mod_revision.NULL_REVISION
961
or end_rev_id == _mod_revision.NULL_REVISION):
962
raise errors.BzrCommandError('Logging revision 0 is invalid.')
963
if start_revno > end_revno:
964
raise errors.BzrCommandError("Start revision must be older than "
966
return (start_rev_id, end_rev_id)
969
def _get_mainline_revs(branch, start_revision, end_revision):
970
"""Get the mainline revisions from the branch.
972
Generates the list of mainline revisions for the branch.
974
:param branch: The branch containing the revisions.
976
:param start_revision: The first revision to be logged.
977
For backwards compatibility this may be a mainline integer revno,
978
but for merge revision support a RevisionInfo is expected.
980
:param end_revision: The last revision to be logged.
981
For backwards compatibility this may be a mainline integer revno,
982
but for merge revision support a RevisionInfo is expected.
984
:return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
986
branch_revno, branch_last_revision = branch.last_revision_info()
987
if branch_revno == 0:
988
return None, None, None, None
990
# For mainline generation, map start_revision and end_revision to
991
# mainline revnos. If the revision is not on the mainline choose the
992
# appropriate extreme of the mainline instead - the extra will be
994
# Also map the revisions to rev_ids, to be used in the later filtering
997
if start_revision is None:
1000
if isinstance(start_revision, revisionspec.RevisionInfo):
1001
start_rev_id = start_revision.rev_id
1002
start_revno = start_revision.revno or 1
1004
branch.check_real_revno(start_revision)
1005
start_revno = start_revision
1008
if end_revision is None:
1009
end_revno = branch_revno
1011
if isinstance(end_revision, revisionspec.RevisionInfo):
1012
end_rev_id = end_revision.rev_id
1013
end_revno = end_revision.revno or branch_revno
1015
branch.check_real_revno(end_revision)
1016
end_revno = end_revision
1018
if ((start_rev_id == _mod_revision.NULL_REVISION)
1019
or (end_rev_id == _mod_revision.NULL_REVISION)):
1020
raise errors.BzrCommandError('Logging revision 0 is invalid.')
1021
if start_revno > end_revno:
1022
raise errors.BzrCommandError("Start revision must be older than "
1023
"the end revision.")
1025
if end_revno < start_revno:
1026
return None, None, None, None
1027
cur_revno = branch_revno
1030
for revision_id in branch.repository.iter_reverse_revision_history(
1031
branch_last_revision):
1032
if cur_revno < start_revno:
1033
# We have gone far enough, but we always add 1 more revision
1034
rev_nos[revision_id] = cur_revno
1035
mainline_revs.append(revision_id)
1037
if cur_revno <= end_revno:
1038
rev_nos[revision_id] = cur_revno
1039
mainline_revs.append(revision_id)
1042
# We walked off the edge of all revisions, so we add a 'None' marker
1043
mainline_revs.append(None)
1045
mainline_revs.reverse()
1047
# override the mainline to look like the revision history.
1048
return mainline_revs, rev_nos, start_rev_id, end_rev_id
1051
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1052
"""Filter view_revisions based on revision ranges.
1054
:param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
1055
tuples to be filtered.
1057
:param start_rev_id: If not NONE specifies the first revision to be logged.
1058
If NONE then all revisions up to the end_rev_id are logged.
1060
:param end_rev_id: If not NONE specifies the last revision to be logged.
1061
If NONE then all revisions up to the end of the log are logged.
1063
:return: The filtered view_revisions.
1065
# This method is no longer called by the main code path.
1066
# It may be removed soon. IGC 20090127
1067
if start_rev_id or end_rev_id:
1068
revision_ids = [r for r, n, d in view_revisions]
1070
start_index = revision_ids.index(start_rev_id)
1073
if start_rev_id == end_rev_id:
1074
end_index = start_index
1077
end_index = revision_ids.index(end_rev_id)
1079
end_index = len(view_revisions) - 1
1080
# To include the revisions merged into the last revision,
1081
# extend end_rev_id down to, but not including, the next rev
1082
# with the same or lesser merge_depth
1083
end_merge_depth = view_revisions[end_index][2]
1085
for index in xrange(end_index+1, len(view_revisions)+1):
1086
if view_revisions[index][2] <= end_merge_depth:
1087
end_index = index - 1
1090
# if the search falls off the end then log to the end as well
1091
end_index = len(view_revisions) - 1
1092
view_revisions = view_revisions[start_index:end_index+1]
1093
return view_revisions
1096
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
1097
include_merges=True):
1098
r"""Return the list of revision ids which touch a given file id.
1100
The function filters view_revisions and returns a subset.
1101
This includes the revisions which directly change the file id,
1102
and the revisions which merge these changes. So if the
1114
And 'C' changes a file, then both C and D will be returned. F will not be
1115
returned even though it brings the changes to C into the branch starting
1116
with E. (Note that if we were using F as the tip instead of G, then we
1119
This will also be restricted based on a subset of the mainline.
1121
:param branch: The branch where we can get text revision information.
1123
:param file_id: Filter out revisions that do not touch file_id.
1125
:param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
1126
tuples. This is the list of revisions which will be filtered. It is
1127
assumed that view_revisions is in merge_sort order (i.e. newest
1130
:param include_merges: include merge revisions in the result or not
1132
:return: A list of (revision_id, dotted_revno, merge_depth) tuples.
1134
# Lookup all possible text keys to determine which ones actually modified
1136
text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
1138
# Looking up keys in batches of 1000 can cut the time in half, as well as
1139
# memory consumption. GraphIndex *does* like to look for a few keys in
1140
# parallel, it just doesn't like looking for *lots* of keys in parallel.
1141
# TODO: This code needs to be re-evaluated periodically as we tune the
1142
# indexing layer. We might consider passing in hints as to the known
1143
# access pattern (sparse/clustered, high success rate/low success
1144
# rate). This particular access is clustered with a low success rate.
1145
get_parent_map = branch.repository.texts.get_parent_map
1146
modified_text_revisions = set()
1148
for start in xrange(0, len(text_keys), chunk_size):
1149
next_keys = text_keys[start:start + chunk_size]
1150
# Only keep the revision_id portion of the key
1151
modified_text_revisions.update(
1152
[k[1] for k in get_parent_map(next_keys)])
1153
del text_keys, next_keys
1156
# Track what revisions will merge the current revision, replace entries
1157
# with 'None' when they have been added to result
1158
current_merge_stack = [None]
1159
for info in view_revisions:
1160
rev_id, revno, depth = info
1161
if depth == len(current_merge_stack):
1162
current_merge_stack.append(info)
1164
del current_merge_stack[depth + 1:]
1165
current_merge_stack[-1] = info
1167
if rev_id in modified_text_revisions:
1168
# This needs to be logged, along with the extra revisions
1169
for idx in xrange(len(current_merge_stack)):
1170
node = current_merge_stack[idx]
1171
if node is not None:
1172
if include_merges or node[2] == 0:
1174
current_merge_stack[idx] = None
1178
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1179
include_merges=True):
1180
"""Produce an iterator of revisions to show
1181
:return: an iterator of (revision_id, revno, merge_depth)
1182
(if there is no revno for a revision, None is supplied)
1184
# This method is no longer called by the main code path.
1185
# It is retained for API compatibility and may be deprecated
1186
# soon. IGC 20090127
1187
if not include_merges:
1188
revision_ids = mainline_revs[1:]
1189
if direction == 'reverse':
1190
revision_ids.reverse()
1191
for revision_id in revision_ids:
1192
yield revision_id, str(rev_nos[revision_id]), 0
1194
graph = branch.repository.get_graph()
1195
# This asks for all mainline revisions, which means we only have to spider
1196
# sideways, rather than depth history. That said, its still size-of-history
1197
# and should be addressed.
1198
# mainline_revisions always includes an extra revision at the beginning, so
1200
parent_map = dict(((key, value) for key, value in
1201
graph.iter_ancestry(mainline_revs[1:]) if value is not None))
1202
# filter out ghosts; merge_sort errors on ghosts.
1203
rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
1204
merge_sorted_revisions = tsort.merge_sort(
1208
generate_revno=True)
1210
if direction == 'forward':
1211
# forward means oldest first.
1212
merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1213
elif direction != 'reverse':
1214
raise ValueError('invalid direction %r' % direction)
1216
for (sequence, rev_id, merge_depth, revno, end_of_merge
1217
) in merge_sorted_revisions:
1218
yield rev_id, '.'.join(map(str, revno)), merge_depth
1221
def reverse_by_depth(merge_sorted_revisions, _depth=0):
1222
"""Reverse revisions by depth.
1224
Revisions with a different depth are sorted as a group with the previous
1225
revision of that depth. There may be no topological justification for this,
1226
but it looks much nicer.
1228
# Add a fake revision at start so that we can always attach sub revisions
1229
merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1231
for val in merge_sorted_revisions:
1232
if val[2] == _depth:
1233
# Each revision at the current depth becomes a chunk grouping all
1234
# higher depth revisions.
1235
zd_revisions.append([val])
1237
zd_revisions[-1].append(val)
1238
for revisions in zd_revisions:
1239
if len(revisions) > 1:
1240
# We have higher depth revisions, let reverse them locally
1241
revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1242
zd_revisions.reverse()
1244
for chunk in zd_revisions:
1245
result.extend(chunk)
1247
# Top level call, get rid of the fake revisions that have been added
1248
result = [r for r in result if r[0] is not None and r[1] is not None]
1252
class LogRevision(object):
1253
"""A revision to be logged (by LogFormatter.log_revision).
1255
A simple wrapper for the attributes of a revision to be logged.
1256
The attributes may or may not be populated, as determined by the
1257
logging options and the log formatter capabilities.
1260
def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1261
tags=None, diff=None):
1263
self.revno = str(revno)
1264
self.merge_depth = merge_depth
1270
class LogFormatter(object):
1271
"""Abstract class to display log messages.
1273
At a minimum, a derived class must implement the log_revision method.
1275
If the LogFormatter needs to be informed of the beginning or end of
1276
a log it should implement the begin_log and/or end_log hook methods.
1278
A LogFormatter should define the following supports_XXX flags
1279
to indicate which LogRevision attributes it supports:
1281
- supports_delta must be True if this log formatter supports delta.
1282
Otherwise the delta attribute may not be populated. The 'delta_format'
1283
attribute describes whether the 'short_status' format (1) or the long
1284
one (2) should be used.
1286
- supports_merge_revisions must be True if this log formatter supports
1287
merge revisions. If not, and if supports_single_merge_revision is
1288
also not True, then only mainline revisions will be passed to the
1291
- preferred_levels is the number of levels this formatter defaults to.
1292
The default value is zero meaning display all levels.
1293
This value is only relevant if supports_merge_revisions is True.
1295
- supports_single_merge_revision must be True if this log formatter
1296
supports logging only a single merge revision. This flag is
1297
only relevant if supports_merge_revisions is not True.
1299
- supports_tags must be True if this log formatter supports tags.
1300
Otherwise the tags attribute may not be populated.
1302
- supports_diff must be True if this log formatter supports diffs.
1303
Otherwise the diff attribute may not be populated.
1305
Plugins can register functions to show custom revision properties using
1306
the properties_handler_registry. The registered function
1307
must respect the following interface description:
1308
def my_show_properties(properties_dict):
1309
# code that returns a dict {'name':'value'} of the properties
1312
preferred_levels = 0
1314
def __init__(self, to_file, show_ids=False, show_timezone='original',
1315
delta_format=None, levels=None):
1316
"""Create a LogFormatter.
1318
:param to_file: the file to output to
1319
:param show_ids: if True, revision-ids are to be displayed
1320
:param show_timezone: the timezone to use
1321
:param delta_format: the level of delta information to display
1322
or None to leave it u to the formatter to decide
1323
:param levels: the number of levels to display; None or -1 to
1324
let the log formatter decide.
1326
self.to_file = to_file
1327
# 'exact' stream used to show diff, it should print content 'as is'
1328
# and should not try to decode/encode it to unicode to avoid bug #328007
1329
self.to_exact_file = getattr(to_file, 'stream', to_file)
1330
self.show_ids = show_ids
1331
self.show_timezone = show_timezone
1332
if delta_format is None:
1333
# Ensures backward compatibility
1334
delta_format = 2 # long format
1335
self.delta_format = delta_format
1336
self.levels = levels
1337
self._merge_count = 0
1339
def get_levels(self):
1340
"""Get the number of levels to display or 0 for all."""
1341
if getattr(self, 'supports_merge_revisions', False):
1342
if self.levels is None or self.levels == -1:
1343
return self.preferred_levels
1348
def log_revision(self, revision):
1351
:param revision: The LogRevision to be logged.
1353
raise NotImplementedError('not implemented in abstract base')
1355
def show_advice(self):
1356
"""Output user advice, if any, when the log is completed."""
1357
if self.levels == 1 and self._merge_count > 0:
1358
advice_sep = self.get_advice_separator()
1360
self.to_file.write(advice_sep)
1362
"Use --levels 0 (or -n0) to see merged revisions.\n")
1364
def get_advice_separator(self):
1365
"""Get the text separating the log from the closing advice."""
1368
def short_committer(self, rev):
1369
name, address = config.parse_username(rev.committer)
1374
def short_author(self, rev):
1375
name, address = config.parse_username(rev.get_apparent_authors()[0])
1380
def merge_marker(self, revision):
1381
"""Get the merge marker to include in the output or '' if none."""
1382
if len(revision.rev.parent_ids) > 1:
1383
self._merge_count += 1
1388
def show_properties(self, revision, indent):
1389
"""Displays the custom properties returned by each registered handler.
1391
If a registered handler raises an error it is propagated.
1393
for key, handler in properties_handler_registry.iteritems():
1394
for key, value in handler(revision).items():
1395
self.to_file.write(indent + key + ': ' + value + '\n')
1397
def show_diff(self, to_file, diff, indent):
1398
for l in diff.rstrip().split('\n'):
1399
to_file.write(indent + '%s\n' % (l,))
1402
class LongLogFormatter(LogFormatter):
1404
supports_merge_revisions = True
1405
supports_delta = True
1406
supports_tags = True
1407
supports_diff = True
1409
def log_revision(self, revision):
1410
"""Log a revision, either merged or not."""
1411
indent = ' ' * revision.merge_depth
1412
to_file = self.to_file
1413
to_file.write(indent + '-' * 60 + '\n')
1414
if revision.revno is not None:
1415
to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
1416
self.merge_marker(revision)))
1418
to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1420
to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1422
for parent_id in revision.rev.parent_ids:
1423
to_file.write(indent + 'parent: %s\n' % (parent_id,))
1424
self.show_properties(revision.rev, indent)
1426
committer = revision.rev.committer
1427
authors = revision.rev.get_apparent_authors()
1428
if authors != [committer]:
1429
to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1430
to_file.write(indent + 'committer: %s\n' % (committer,))
1432
branch_nick = revision.rev.properties.get('branch-nick', None)
1433
if branch_nick is not None:
1434
to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
1436
date_str = format_date(revision.rev.timestamp,
1437
revision.rev.timezone or 0,
1439
to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1441
to_file.write(indent + 'message:\n')
1442
if not revision.rev.message:
1443
to_file.write(indent + ' (no message)\n')
1445
message = revision.rev.message.rstrip('\r\n')
1446
for l in message.split('\n'):
1447
to_file.write(indent + ' %s\n' % (l,))
1448
if revision.delta is not None:
1449
# We don't respect delta_format for compatibility
1450
revision.delta.show(to_file, self.show_ids, indent=indent,
1452
if revision.diff is not None:
1453
to_file.write(indent + 'diff:\n')
1454
# Note: we explicitly don't indent the diff (relative to the
1455
# revision information) so that the output can be fed to patch -p0
1456
self.show_diff(self.to_exact_file, revision.diff, indent)
1458
def get_advice_separator(self):
1459
"""Get the text separating the log from the closing advice."""
1460
return '-' * 60 + '\n'
1463
class ShortLogFormatter(LogFormatter):
1465
supports_merge_revisions = True
1466
preferred_levels = 1
1467
supports_delta = True
1468
supports_tags = True
1469
supports_diff = True
1471
def __init__(self, *args, **kwargs):
1472
super(ShortLogFormatter, self).__init__(*args, **kwargs)
1473
self.revno_width_by_depth = {}
1475
def log_revision(self, revision):
1476
# We need two indents: one per depth and one for the information
1477
# relative to that indent. Most mainline revnos are 5 chars or
1478
# less while dotted revnos are typically 11 chars or less. Once
1479
# calculated, we need to remember the offset for a given depth
1480
# as we might be starting from a dotted revno in the first column
1481
# and we want subsequent mainline revisions to line up.
1482
depth = revision.merge_depth
1483
indent = ' ' * depth
1484
revno_width = self.revno_width_by_depth.get(depth)
1485
if revno_width is None:
1486
if revision.revno.find('.') == -1:
1487
# mainline revno, e.g. 12345
1490
# dotted revno, e.g. 12345.10.55
1492
self.revno_width_by_depth[depth] = revno_width
1493
offset = ' ' * (revno_width + 1)
1495
to_file = self.to_file
1498
tags = ' {%s}' % (', '.join(revision.tags))
1499
to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1500
revision.revno, self.short_author(revision.rev),
1501
format_date(revision.rev.timestamp,
1502
revision.rev.timezone or 0,
1503
self.show_timezone, date_fmt="%Y-%m-%d",
1505
tags, self.merge_marker(revision)))
1506
self.show_properties(revision.rev, indent+offset)
1508
to_file.write(indent + offset + 'revision-id:%s\n'
1509
% (revision.rev.revision_id,))
1510
if not revision.rev.message:
1511
to_file.write(indent + offset + '(no message)\n')
1513
message = revision.rev.message.rstrip('\r\n')
1514
for l in message.split('\n'):
1515
to_file.write(indent + offset + '%s\n' % (l,))
1517
if revision.delta is not None:
1518
revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1519
short_status=self.delta_format==1)
1520
if revision.diff is not None:
1521
self.show_diff(self.to_exact_file, revision.diff, ' ')
1525
class LineLogFormatter(LogFormatter):
1527
supports_merge_revisions = True
1528
preferred_levels = 1
1529
supports_tags = True
1531
def __init__(self, *args, **kwargs):
1532
super(LineLogFormatter, self).__init__(*args, **kwargs)
1533
self._max_chars = terminal_width() - 1
1535
def truncate(self, str, max_len):
1536
if len(str) <= max_len:
1538
return str[:max_len-3]+'...'
1540
def date_string(self, rev):
1541
return format_date(rev.timestamp, rev.timezone or 0,
1542
self.show_timezone, date_fmt="%Y-%m-%d",
1545
def message(self, rev):
1547
return '(no message)'
1551
def log_revision(self, revision):
1552
indent = ' ' * revision.merge_depth
1553
self.to_file.write(self.log_string(revision.revno, revision.rev,
1554
self._max_chars, revision.tags, indent))
1555
self.to_file.write('\n')
1557
def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1558
"""Format log info into one string. Truncate tail of string
1559
:param revno: revision number or None.
1560
Revision numbers counts from 1.
1561
:param rev: revision object
1562
:param max_chars: maximum length of resulting string
1563
:param tags: list of tags or None
1564
:param prefix: string to prefix each line
1565
:return: formatted truncated string
1569
# show revno only when is not None
1570
out.append("%s:" % revno)
1571
out.append(self.truncate(self.short_author(rev), 20))
1572
out.append(self.date_string(rev))
1573
if len(rev.parent_ids) > 1:
1574
out.append('[merge]')
1576
tag_str = '{%s}' % (', '.join(tags))
1578
out.append(rev.get_summary())
1579
return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
1582
class GnuChangelogLogFormatter(LogFormatter):
1584
supports_merge_revisions = True
1585
supports_delta = True
1587
def log_revision(self, revision):
1588
"""Log a revision, either merged or not."""
1589
to_file = self.to_file
1591
date_str = format_date(revision.rev.timestamp,
1592
revision.rev.timezone or 0,
1594
date_fmt='%Y-%m-%d',
1596
committer_str = revision.rev.committer.replace (' <', ' <')
1597
to_file.write('%s %s\n\n' % (date_str,committer_str))
1599
if revision.delta is not None and revision.delta.has_changed():
1600
for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
1602
to_file.write('\t* %s:\n' % (path,))
1603
for c in revision.delta.renamed:
1604
oldpath,newpath = c[:2]
1605
# For renamed files, show both the old and the new path
1606
to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
1609
if not revision.rev.message:
1610
to_file.write('\tNo commit message\n')
1612
message = revision.rev.message.rstrip('\r\n')
1613
for l in message.split('\n'):
1614
to_file.write('\t%s\n' % (l.lstrip(),))
1618
def line_log(rev, max_chars):
1619
lf = LineLogFormatter(None)
1620
return lf.log_string(None, rev, max_chars)
1623
class LogFormatterRegistry(registry.Registry):
1624
"""Registry for log formatters"""
1626
def make_formatter(self, name, *args, **kwargs):
1627
"""Construct a formatter from arguments.
1629
:param name: Name of the formatter to construct. 'short', 'long' and
1630
'line' are built-in.
1632
return self.get(name)(*args, **kwargs)
1634
def get_default(self, branch):
1635
return self.get(branch.get_config().log_format())
1638
log_formatter_registry = LogFormatterRegistry()
1641
log_formatter_registry.register('short', ShortLogFormatter,
1642
'Moderately short log format')
1643
log_formatter_registry.register('long', LongLogFormatter,
1644
'Detailed log format')
1645
log_formatter_registry.register('line', LineLogFormatter,
1646
'Log format with one line per revision')
1647
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
1648
'Format used by GNU ChangeLog files')
1651
def register_formatter(name, formatter):
1652
log_formatter_registry.register(name, formatter)
1655
def log_formatter(name, *args, **kwargs):
1656
"""Construct a formatter from arguments.
1658
name -- Name of the formatter to construct; currently 'long', 'short' and
1659
'line' are supported.
1662
return log_formatter_registry.make_formatter(name, *args, **kwargs)
1664
raise errors.BzrCommandError("unknown log formatter: %r" % name)
1667
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1668
# deprecated; for compatibility
1669
lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1670
lf.show(revno, rev, delta)
1673
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1675
"""Show the change in revision history comparing the old revision history to the new one.
1677
:param branch: The branch where the revisions exist
1678
:param old_rh: The old revision history
1679
:param new_rh: The new revision history
1680
:param to_file: A file to write the results to. If None, stdout will be used
1683
to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1685
lf = log_formatter(log_format,
1688
show_timezone='original')
1690
# This is the first index which is different between
1693
for i in xrange(max(len(new_rh),
1695
if (len(new_rh) <= i
1697
or new_rh[i] != old_rh[i]):
1701
if base_idx is None:
1702
to_file.write('Nothing seems to have changed\n')
1704
## TODO: It might be nice to do something like show_log
1705
## and show the merged entries. But since this is the
1706
## removed revisions, it shouldn't be as important
1707
if base_idx < len(old_rh):
1708
to_file.write('*'*60)
1709
to_file.write('\nRemoved Revisions:\n')
1710
for i in range(base_idx, len(old_rh)):
1711
rev = branch.repository.get_revision(old_rh[i])
1712
lr = LogRevision(rev, i+1, 0, None)
1714
to_file.write('*'*60)
1715
to_file.write('\n\n')
1716
if base_idx < len(new_rh):
1717
to_file.write('Added Revisions:\n')
1722
direction='forward',
1723
start_revision=base_idx+1,
1724
end_revision=len(new_rh),
1728
def get_history_change(old_revision_id, new_revision_id, repository):
1729
"""Calculate the uncommon lefthand history between two revisions.
1731
:param old_revision_id: The original revision id.
1732
:param new_revision_id: The new revision id.
1733
:param repository: The repository to use for the calculation.
1735
return old_history, new_history
1738
old_revisions = set()
1740
new_revisions = set()
1741
new_iter = repository.iter_reverse_revision_history(new_revision_id)
1742
old_iter = repository.iter_reverse_revision_history(old_revision_id)
1743
stop_revision = None
1746
while do_new or do_old:
1749
new_revision = new_iter.next()
1750
except StopIteration:
1753
new_history.append(new_revision)
1754
new_revisions.add(new_revision)
1755
if new_revision in old_revisions:
1756
stop_revision = new_revision
1760
old_revision = old_iter.next()
1761
except StopIteration:
1764
old_history.append(old_revision)
1765
old_revisions.add(old_revision)
1766
if old_revision in new_revisions:
1767
stop_revision = old_revision
1769
new_history.reverse()
1770
old_history.reverse()
1771
if stop_revision is not None:
1772
new_history = new_history[new_history.index(stop_revision) + 1:]
1773
old_history = old_history[old_history.index(stop_revision) + 1:]
1774
return old_history, new_history
1777
def show_branch_change(branch, output, old_revno, old_revision_id):
1778
"""Show the changes made to a branch.
1780
:param branch: The branch to show changes about.
1781
:param output: A file-like object to write changes to.
1782
:param old_revno: The revno of the old tip.
1783
:param old_revision_id: The revision_id of the old tip.
1785
new_revno, new_revision_id = branch.last_revision_info()
1786
old_history, new_history = get_history_change(old_revision_id,
1789
if old_history == [] and new_history == []:
1790
output.write('Nothing seems to have changed\n')
1793
log_format = log_formatter_registry.get_default(branch)
1794
lf = log_format(show_ids=False, to_file=output, show_timezone='original')
1795
if old_history != []:
1796
output.write('*'*60)
1797
output.write('\nRemoved Revisions:\n')
1798
show_flat_log(branch.repository, old_history, old_revno, lf)
1799
output.write('*'*60)
1800
output.write('\n\n')
1801
if new_history != []:
1802
output.write('Added Revisions:\n')
1803
start_revno = new_revno - len(new_history) + 1
1804
show_log(branch, lf, None, verbose=False, direction='forward',
1805
start_revision=start_revno,)
1808
def show_flat_log(repository, history, last_revno, lf):
1809
"""Show a simple log of the specified history.
1811
:param repository: The repository to retrieve revisions from.
1812
:param history: A list of revision_ids indicating the lefthand history.
1813
:param last_revno: The revno of the last revision_id in the history.
1814
:param lf: The log formatter to use.
1816
start_revno = last_revno - len(history) + 1
1817
revisions = repository.get_revisions(history)
1818
for i, rev in enumerate(revisions):
1819
lr = LogRevision(rev, i + last_revno, 0, None)
1823
def _get_info_for_log_files(revisionspec_list, file_list):
1824
"""Find file-ids and kinds given a list of files and a revision range.
1826
We search for files at the end of the range. If not found there,
1827
we try the start of the range.
1829
:param revisionspec_list: revision range as parsed on the command line
1830
:param file_list: the list of paths given on the command line;
1831
the first of these can be a branch location or a file path,
1832
the remainder must be file paths
1833
:return: (branch, info_list, start_rev_info, end_rev_info) where
1834
info_list is a list of (relative_path, file_id, kind) tuples where
1835
kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
1837
from builtins import _get_revision_range, safe_relpath_files
1838
tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
1839
# XXX: It's damn messy converting a list of paths to relative paths when
1840
# those paths might be deleted ones, they might be on a case-insensitive
1841
# filesystem and/or they might be in silly locations (like another branch).
1842
# For example, what should "log bzr://branch/dir/file1 file2" do? (Is
1843
# file2 implicitly in the same dir as file1 or should its directory be
1844
# taken from the current tree somehow?) For now, this solves the common
1845
# case of running log in a nested directory, assuming paths beyond the
1846
# first one haven't been deleted ...
1848
relpaths = [path] + safe_relpath_files(tree, file_list[1:])
1850
relpaths = [path] + file_list[1:]
1852
start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
1854
if start_rev_info is None and end_rev_info is None:
1856
tree = b.basis_tree()
1859
file_id = tree.path2id(fp)
1860
kind = _get_kind_for_file_id(tree, file_id)
1862
# go back to when time began
1865
rev1 = b.get_rev_id(1)
1866
except errors.NoSuchRevision:
1871
tree1 = b.repository.revision_tree(rev1)
1873
file_id = tree1.path2id(fp)
1874
kind = _get_kind_for_file_id(tree1, file_id)
1875
info_list.append((fp, file_id, kind))
1877
elif start_rev_info == end_rev_info:
1878
# One revision given - file must exist in it
1879
tree = b.repository.revision_tree(end_rev_info.rev_id)
1881
file_id = tree.path2id(fp)
1882
kind = _get_kind_for_file_id(tree, file_id)
1883
info_list.append((fp, file_id, kind))
1886
# Revision range given. Get the file-id from the end tree.
1887
# If that fails, try the start tree.
1888
rev_id = end_rev_info.rev_id
1890
tree = b.basis_tree()
1892
tree = b.repository.revision_tree(rev_id)
1895
file_id = tree.path2id(fp)
1896
kind = _get_kind_for_file_id(tree, file_id)
1899
rev_id = start_rev_info.rev_id
1901
rev1 = b.get_rev_id(1)
1902
tree1 = b.repository.revision_tree(rev1)
1904
tree1 = b.repository.revision_tree(rev_id)
1905
file_id = tree1.path2id(fp)
1906
kind = _get_kind_for_file_id(tree1, file_id)
1907
info_list.append((fp, file_id, kind))
1908
return b, info_list, start_rev_info, end_rev_info
1911
def _get_kind_for_file_id(tree, file_id):
1912
"""Return the kind of a file-id or None if it doesn't exist."""
1913
if file_id is not None:
1914
return tree.kind(file_id)
1919
properties_handler_registry = registry.Registry()
1920
properties_handler_registry.register_lazy("foreign",
1922
"show_foreign_properties")
1925
# adapters which revision ids to log are filtered. When log is called, the
1926
# log_rev_iterator is adapted through each of these factory methods.
1927
# Plugins are welcome to mutate this list in any way they like - as long
1928
# as the overall behaviour is preserved. At this point there is no extensible
1929
# mechanism for getting parameters to each factory method, and until there is
1930
# this won't be considered a stable api.
1934
# read revision objects
1935
_make_revision_objects,
1936
# filter on log messages
1937
_make_search_filter,
1938
# generate deltas for things we will show