172
199
# list indexes are 0-based; revisions are 1-based
173
200
cut_revs = which_revs[(start_revision-1):(end_revision)]
175
if direction == 'reverse':
177
elif direction == 'forward':
180
raise ValueError('invalid direction %r' % direction)
182
for revno, rev_id in cut_revs:
183
if verbose or specific_fileid:
184
delta = branch.get_revision_delta(revno)
204
# convert the revision history to a dictionary:
205
rev_nos = dict((k, v) for v, k in cut_revs)
207
# override the mainline to look like the revision history.
208
mainline_revs = [revision_id for index, revision_id in cut_revs]
209
if cut_revs[0][0] == 1:
210
mainline_revs.insert(0, None)
212
mainline_revs.insert(0, which_revs[start_revision-2][1])
213
# how should we show merged revisions ?
214
# old api: show_merge. New api: show_merge_revno
215
show_merge_revno = getattr(lf, 'show_merge_revno', None)
216
show_merge = getattr(lf, 'show_merge', None)
217
if show_merge is None and show_merge_revno is None:
218
# no merged-revno support
219
include_merges = False
221
include_merges = True
222
if show_merge is not None and show_merge_revno is None:
223
# tell developers to update their code
224
symbol_versioning.warn('LogFormatters should provide show_merge_revno '
225
'instead of show_merge since bzr 0.11.',
226
DeprecationWarning, stacklevel=3)
227
view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
228
direction, include_merges=include_merges)
230
view_revisions = _get_revisions_touching_file_id(branch,
235
view_revisions = list(view_revs_iter)
237
use_tags = getattr(lf, 'supports_tags', False)
240
if branch.supports_tags():
241
rev_tag_dict = branch.tags.get_reverse_tag_dict()
243
def iter_revisions():
244
# r = revision, n = revno, d = merge depth
245
revision_ids = [r for r, n, d in view_revisions]
246
zeros = set(r for r, n, d in view_revisions if d == 0)
248
repository = branch.repository
251
revisions = repository.get_revisions(revision_ids[:num])
253
delta_revisions = [r for r in revisions if
254
r.revision_id in zeros]
255
deltas = repository.get_deltas_for_revisions(delta_revisions)
256
cur_deltas = dict(izip((r.revision_id for r in
257
delta_revisions), deltas))
258
for revision in revisions:
259
# The delta value will be None unless
260
# 1. verbose is specified, and
261
# 2. the revision is a mainline revision
262
yield revision, cur_deltas.get(revision.revision_id)
263
revision_ids = revision_ids[num:]
264
num = min(int(num * 1.5), 200)
187
if not delta.touches_file_id(specific_fileid):
191
# although we calculated it, throw it away without display
194
rev = branch.get_revision(rev_id)
266
# now we just print all the revisions
267
for ((rev_id, revno, merge_depth), (rev, delta)) in \
268
izip(view_revisions, iter_revisions()):
197
271
if not searchRE.search(rev.message):
200
lf.show(revno, rev, delta)
204
def deltas_for_log_dummy(branch, which_revs):
205
"""Return all the revisions without intermediate deltas.
207
Useful for log commands that won't need the delta information.
210
for revno, revision_id in which_revs:
211
yield revno, branch.get_revision(revision_id), None
214
def deltas_for_log_reverse(branch, which_revs):
215
"""Compute deltas for display in latest-to-earliest order.
221
Sequence of (revno, revision_id) for the subset of history to examine
224
Sequence of (revno, rev, delta)
226
The delta is from the given revision to the next one in the
227
sequence, which makes sense if the log is being displayed from
230
last_revno = last_revision_id = last_tree = None
231
for revno, revision_id in which_revs:
232
this_tree = branch.revision_tree(revision_id)
233
this_revision = branch.get_revision(revision_id)
236
yield last_revno, last_revision, compare_trees(this_tree, last_tree, False)
238
this_tree = EmptyTree(branch.get_root_id())
241
last_revision = this_revision
242
last_tree = this_tree
246
this_tree = EmptyTree(branch.get_root_id())
248
this_revno = last_revno - 1
249
this_revision_id = branch.revision_history()[this_revno]
250
this_tree = branch.revision_tree(this_revision_id)
251
yield last_revno, last_revision, compare_trees(this_tree, last_tree, False)
254
def deltas_for_log_forward(branch, which_revs):
255
"""Compute deltas for display in forward log.
257
Given a sequence of (revno, revision_id) pairs, return
260
The delta is from the given revision to the next one in the
261
sequence, which makes sense if the log is being displayed from
264
last_revno = last_revision_id = last_tree = None
265
prev_tree = EmptyTree(branch.get_root_id())
267
for revno, revision_id in which_revs:
268
this_tree = branch.revision_tree(revision_id)
269
this_revision = branch.get_revision(revision_id)
273
last_tree = EmptyTree(branch.get_root_id())
275
last_revno = revno - 1
276
last_revision_id = branch.revision_history()[last_revno]
277
last_tree = branch.revision_tree(last_revision_id)
279
yield revno, this_revision, compare_trees(last_tree, this_tree, False)
282
last_revision = this_revision
283
last_tree = this_tree
276
lf.show(revno, rev, delta, rev_tag_dict.get(rev_id))
278
lf.show(revno, rev, delta)
280
if show_merge_revno is None:
281
lf.show_merge(rev, merge_depth)
284
lf.show_merge_revno(rev, merge_depth, revno,
285
rev_tag_dict.get(rev_id))
287
lf.show_merge_revno(rev, merge_depth, revno)
290
def _get_revisions_touching_file_id(branch, file_id, mainline_revisions,
292
"""Return the list of revision ids which touch a given file id.
294
This includes the revisions which directly change the file id,
295
and the revisions which merge these changes. So if the
303
And 'C' changes a file, then both C and D will be returned.
305
This will also can be restricted based on a subset of the mainline.
307
:return: A list of (revision_id, dotted_revno, merge_depth) tuples.
309
# find all the revisions that change the specific file
310
file_weave = branch.repository.weave_store.get_weave(file_id,
311
branch.repository.get_transaction())
312
weave_modifed_revisions = set(file_weave.versions())
313
# build the ancestry of each revision in the graph
314
# - only listing the ancestors that change the specific file.
315
rev_graph = branch.repository.get_revision_graph(mainline_revisions[-1])
316
sorted_rev_list = topo_sort(rev_graph)
318
for rev in sorted_rev_list:
319
parents = rev_graph[rev]
320
if rev not in weave_modifed_revisions and len(parents) == 1:
321
# We will not be adding anything new, so just use a reference to
322
# the parent ancestry.
323
rev_ancestry = ancestry[parents[0]]
326
if rev in weave_modifed_revisions:
327
rev_ancestry.add(rev)
328
for parent in parents:
329
rev_ancestry = rev_ancestry.union(ancestry[parent])
330
ancestry[rev] = rev_ancestry
332
def is_merging_rev(r):
333
parents = rev_graph[r]
335
leftparent = parents[0]
336
for rightparent in parents[1:]:
337
if not ancestry[leftparent].issuperset(
338
ancestry[rightparent]):
342
# filter from the view the revisions that did not change or merge
344
return [(r, n, d) for r, n, d in view_revs_iter
345
if r in weave_modifed_revisions or is_merging_rev(r)]
348
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
349
include_merges=True):
350
"""Produce an iterator of revisions to show
351
:return: an iterator of (revision_id, revno, merge_depth)
352
(if there is no revno for a revision, None is supplied)
354
if include_merges is False:
355
revision_ids = mainline_revs[1:]
356
if direction == 'reverse':
357
revision_ids.reverse()
358
for revision_id in revision_ids:
359
yield revision_id, str(rev_nos[revision_id]), 0
361
merge_sorted_revisions = merge_sort(
362
branch.repository.get_revision_graph(mainline_revs[-1]),
367
if direction == 'forward':
368
# forward means oldest first.
369
merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
370
elif direction != 'reverse':
371
raise ValueError('invalid direction %r' % direction)
373
for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
374
yield rev_id, '.'.join(map(str, revno)), merge_depth
377
def reverse_by_depth(merge_sorted_revisions, _depth=0):
378
"""Reverse revisions by depth.
380
Revisions with a different depth are sorted as a group with the previous
381
revision of that depth. There may be no topological justification for this,
382
but it looks much nicer.
385
for val in merge_sorted_revisions:
387
zd_revisions.append([val])
389
assert val[2] > _depth
390
zd_revisions[-1].append(val)
391
for revisions in zd_revisions:
392
if len(revisions) > 1:
393
revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
394
zd_revisions.reverse()
396
for chunk in zd_revisions:
286
401
class LogFormatter(object):
287
402
"""Abstract class to display log messages."""
288
404
def __init__(self, to_file, show_ids=False, show_timezone='original'):
289
405
self.to_file = to_file
290
406
self.show_ids = show_ids
291
407
self.show_timezone = show_timezone
294
409
def show(self, revno, rev, delta):
295
410
raise NotImplementedError('not implemented in abstract base')
412
def short_committer(self, rev):
413
return re.sub('<.*@.*>', '', rev.committer).strip(' ')
302
416
class LongLogFormatter(LogFormatter):
303
def show(self, revno, rev, delta):
304
from osutils import format_date
418
supports_tags = True # must exist and be True
419
# if this log formatter support tags.
420
# .show() and .show_merge_revno() must then accept
421
# the 'tags'-argument with list of tags
423
def show(self, revno, rev, delta, tags=None):
424
return self._show_helper(revno=revno, rev=rev, delta=delta, tags=tags)
426
@deprecated_method(zero_eleven)
427
def show_merge(self, rev, merge_depth):
428
return self._show_helper(rev=rev, indent=' '*merge_depth,
429
merged=True, delta=None)
431
def show_merge_revno(self, rev, merge_depth, revno, tags=None):
432
"""Show a merged revision rev, with merge_depth and a revno."""
433
return self._show_helper(rev=rev, revno=revno,
434
indent=' '*merge_depth, merged=True, delta=None, tags=tags)
436
def _show_helper(self, rev=None, revno=None, indent='', merged=False,
437
delta=None, tags=None):
438
"""Show a revision, either merged or not."""
439
from bzrlib.osutils import format_date
306
440
to_file = self.to_file
308
print >>to_file, '-' * 60
309
print >>to_file, 'revno:', revno
441
print >>to_file, indent+'-' * 60
442
if revno is not None:
443
print >>to_file, indent+'revno:', revno
445
print >>to_file, indent+'tags: %s' % (', '.join(tags))
447
print >>to_file, indent+'merged:', rev.revision_id
449
print >>to_file, indent+'revision-id:', rev.revision_id
310
450
if self.show_ids:
311
print >>to_file, 'revision-id:', rev.revision_id
313
for parent in rev.parents:
314
print >>to_file, 'parent:', parent.revision_id
316
print >>to_file, 'committer:', rev.committer
451
for parent_id in rev.parent_ids:
452
print >>to_file, indent+'parent:', parent_id
453
print >>to_file, indent+'committer:', rev.committer
456
print >>to_file, indent+'branch nick: %s' % \
457
rev.properties['branch-nick']
318
460
date_str = format_date(rev.timestamp,
319
461
rev.timezone or 0,
320
462
self.show_timezone)
321
print >>to_file, 'timestamp: %s' % date_str
463
print >>to_file, indent+'timestamp: %s' % date_str
323
print >>to_file, 'message:'
465
print >>to_file, indent+'message:'
324
466
if not rev.message:
325
print >>to_file, ' (no message)'
467
print >>to_file, indent+' (no message)'
327
for l in rev.message.split('\n'):
328
print >>to_file, ' ' + l
469
message = rev.message.rstrip('\r\n')
470
for l in message.split('\n'):
471
print >>to_file, indent+' ' + l
472
if delta is not None:
331
473
delta.show(to_file, self.show_ids)
335
476
class ShortLogFormatter(LogFormatter):
336
477
def show(self, revno, rev, delta):
337
478
from bzrlib.osutils import format_date
339
480
to_file = self.to_file
341
print >>to_file, "%5d %s\t%s" % (revno, rev.committer,
481
date_str = format_date(rev.timestamp, rev.timezone or 0,
483
print >>to_file, "%5s %s\t%s" % (revno, self.short_committer(rev),
342
484
format_date(rev.timestamp, rev.timezone or 0,
485
self.show_timezone, date_fmt="%Y-%m-%d",
344
487
if self.show_ids:
345
488
print >>to_file, ' revision-id:', rev.revision_id
346
489
if not rev.message:
347
490
print >>to_file, ' (no message)'
349
for l in rev.message.split('\n'):
492
message = rev.message.rstrip('\r\n')
493
for l in message.split('\n'):
350
494
print >>to_file, ' ' + l
352
496
# TODO: Why not show the modified files in a shorter form as
353
497
# well? rewrap them single lines of appropriate length
498
if delta is not None:
355
499
delta.show(to_file, self.show_ids)
360
FORMATTERS = {'long': LongLogFormatter,
361
'short': ShortLogFormatter,
503
class LineLogFormatter(LogFormatter):
504
def truncate(self, str, max_len):
505
if len(str) <= max_len:
507
return str[:max_len-3]+'...'
509
def date_string(self, rev):
510
from bzrlib.osutils import format_date
511
return format_date(rev.timestamp, rev.timezone or 0,
512
self.show_timezone, date_fmt="%Y-%m-%d",
515
def message(self, rev):
517
return '(no message)'
521
def show(self, revno, rev, delta):
522
from bzrlib.osutils import terminal_width
523
print >> self.to_file, self.log_string(revno, rev, terminal_width()-1)
525
def log_string(self, revno, rev, max_chars):
526
"""Format log info into one string. Truncate tail of string
527
:param revno: revision number (int) or None.
528
Revision numbers counts from 1.
529
:param rev: revision info object
530
:param max_chars: maximum length of resulting string
531
:return: formatted truncated string
535
# show revno only when is not None
536
out.append("%s:" % revno)
537
out.append(self.truncate(self.short_committer(rev), 20))
538
out.append(self.date_string(rev))
539
out.append(rev.get_summary())
540
return self.truncate(" ".join(out).rstrip('\n'), max_chars)
543
def line_log(rev, max_chars):
544
lf = LineLogFormatter(None)
545
return lf.log_string(None, rev, max_chars)
548
class LogFormatterRegistry(registry.Registry):
549
"""Registry for log formatters"""
551
def make_formatter(self, name, *args, **kwargs):
552
"""Construct a formatter from arguments.
554
:param name: Name of the formatter to construct. 'short', 'long' and
557
return self.get(name)(*args, **kwargs)
559
def get_default(self, branch):
560
return self.get(branch.get_config().log_format())
563
log_formatter_registry = LogFormatterRegistry()
566
log_formatter_registry.register('short', ShortLogFormatter,
567
'Moderately short log format')
568
log_formatter_registry.register('long', LongLogFormatter,
569
'Detailed log format')
570
log_formatter_registry.register('line', LineLogFormatter,
571
'Log format with one line per revision')
574
def register_formatter(name, formatter):
575
log_formatter_registry.register(name, formatter)
365
578
def log_formatter(name, *args, **kwargs):
579
"""Construct a formatter from arguments.
581
name -- Name of the formatter to construct; currently 'long', 'short' and
582
'line' are supported.
366
584
from bzrlib.errors import BzrCommandError
369
return FORMATTERS[name](*args, **kwargs)
586
return log_formatter_registry.make_formatter(name, *args, **kwargs)
371
588
raise BzrCommandError("unknown log formatter: %r" % name)
373
591
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
374
# deprecated; for compatability
592
# deprecated; for compatibility
375
593
lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
376
594
lf.show(revno, rev, delta)
596
def show_changed_revisions(branch, old_rh, new_rh, to_file=None, log_format='long'):
597
"""Show the change in revision history comparing the old revision history to the new one.
599
:param branch: The branch where the revisions exist
600
:param old_rh: The old revision history
601
:param new_rh: The new revision history
602
:param to_file: A file to write the results to. If None, stdout will be used
608
to_file = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
609
lf = log_formatter(log_format,
612
show_timezone='original')
614
# This is the first index which is different between
617
for i in xrange(max(len(new_rh),
621
or new_rh[i] != old_rh[i]):
626
to_file.write('Nothing seems to have changed\n')
628
## TODO: It might be nice to do something like show_log
629
## and show the merged entries. But since this is the
630
## removed revisions, it shouldn't be as important
631
if base_idx < len(old_rh):
632
to_file.write('*'*60)
633
to_file.write('\nRemoved Revisions:\n')
634
for i in range(base_idx, len(old_rh)):
635
rev = branch.repository.get_revision(old_rh[i])
636
lf.show(i+1, rev, None)
637
to_file.write('*'*60)
638
to_file.write('\n\n')
639
if base_idx < len(new_rh):
640
to_file.write('Added Revisions:\n')
646
start_revision=base_idx+1,
647
end_revision=len(new_rh),