174
188
:param show_diff: If True, output a diff after each revision.
178
if getattr(lf, 'begin_log', None):
181
_show_log(branch, lf, specific_fileid, verbose, direction,
182
start_revision, end_revision, search, limit, show_diff)
184
if getattr(lf, 'end_log', None):
190
def _show_log(branch,
192
specific_fileid=None,
200
"""Worker function for show_log - see show_log."""
201
if not isinstance(lf, LogFormatter):
202
warn("not a LogFormatter instance: %r" % lf)
204
trace.mutter('get log for file_id %r', specific_fileid)
206
# Consult the LogFormatter about what it needs and can handle
207
levels_to_display = lf.get_levels()
208
generate_merge_revisions = levels_to_display != 1
209
allow_single_merge_revision = True
210
if not getattr(lf, 'supports_merge_revisions', False):
211
allow_single_merge_revision = getattr(lf,
212
'supports_single_merge_revision', False)
213
generate_tags = getattr(lf, 'supports_tags', False)
214
if generate_tags and branch.supports_tags():
215
rev_tag_dict = branch.tags.get_reverse_tag_dict()
218
generate_delta = verbose and getattr(lf, 'supports_delta', False)
219
generate_diff = show_diff and getattr(lf, 'supports_diff', False)
221
# Find and print the interesting revisions
222
repo = branch.repository
224
revision_iterator = _create_log_revision_iterator(branch,
225
start_revision, end_revision, direction, specific_fileid, search,
226
generate_merge_revisions, allow_single_merge_revision,
227
generate_delta, limited_output=limit > 0)
228
for revs in revision_iterator:
229
for (rev_id, revno, merge_depth), rev, delta in revs:
230
# Note: 0 levels means show everything; merge_depth counts from 0
231
if levels_to_display != 0 and merge_depth >= levels_to_display:
234
diff = _format_diff(repo, rev, rev_id, specific_fileid)
237
lr = LogRevision(rev, revno, merge_depth, delta,
238
rev_tag_dict.get(rev_id), diff)
190
# Convert old-style parameters to new-style parameters
191
if specific_fileid is not None:
192
file_ids = [specific_fileid]
197
delta_type = 'partial'
204
diff_type = 'partial'
210
# Build the request and execute it
211
rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
212
start_revision=start_revision, end_revision=end_revision,
213
limit=limit, message_search=search,
214
delta_type=delta_type, diff_type=diff_type)
215
Logger(branch, rqst).show(lf)
218
# Note: This needs to be kept this in sync with the defaults in
219
# make_log_request_dict() below
220
_DEFAULT_REQUEST_PARAMS = {
221
'direction': 'reverse',
223
'generate_tags': True,
224
'exclude_common_ancestry': False,
225
'_match_using_deltas': True,
229
def make_log_request_dict(direction='reverse', specific_fileids=None,
230
start_revision=None, end_revision=None, limit=None,
231
message_search=None, levels=1, generate_tags=True,
233
diff_type=None, _match_using_deltas=True,
234
exclude_common_ancestry=False,
237
"""Convenience function for making a logging request dictionary.
239
Using this function may make code slightly safer by ensuring
240
parameters have the correct names. It also provides a reference
241
point for documenting the supported parameters.
243
:param direction: 'reverse' (default) is latest to earliest;
244
'forward' is earliest to latest.
246
:param specific_fileids: If not None, only include revisions
247
affecting the specified files, rather than all revisions.
249
:param start_revision: If not None, only generate
250
revisions >= start_revision
252
:param end_revision: If not None, only generate
253
revisions <= end_revision
255
:param limit: If set, generate only 'limit' revisions, all revisions
256
are shown if None or 0.
258
:param message_search: If not None, only include revisions with
259
matching commit messages
261
:param levels: the number of levels of revisions to
262
generate; 1 for just the mainline; 0 for all levels.
264
:param generate_tags: If True, include tags for matched revisions.
266
:param delta_type: Either 'full', 'partial' or None.
267
'full' means generate the complete delta - adds/deletes/modifies/etc;
268
'partial' means filter the delta using specific_fileids;
269
None means do not generate any delta.
271
:param diff_type: Either 'full', 'partial' or None.
272
'full' means generate the complete diff - adds/deletes/modifies/etc;
273
'partial' means filter the diff using specific_fileids;
274
None means do not generate any diff.
276
:param _match_using_deltas: a private parameter controlling the
277
algorithm used for matching specific_fileids. This parameter
278
may be removed in the future so bzrlib client code should NOT
281
:param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
282
range operator or as a graph difference.
284
:param signature: show digital signature information
287
'direction': direction,
288
'specific_fileids': specific_fileids,
289
'start_revision': start_revision,
290
'end_revision': end_revision,
292
'message_search': message_search,
294
'generate_tags': generate_tags,
295
'delta_type': delta_type,
296
'diff_type': diff_type,
297
'exclude_common_ancestry': exclude_common_ancestry,
298
'signature': signature,
299
# Add 'private' attributes for features that may be deprecated
300
'_match_using_deltas': _match_using_deltas,
304
def _apply_log_request_defaults(rqst):
305
"""Apply default values to a request dictionary."""
306
result = _DEFAULT_REQUEST_PARAMS.copy()
312
def format_signature_validity(rev_id, repo):
313
"""get the signature validity
315
:param rev_id: revision id to validate
316
:param repo: repository of revision
317
:return: human readable string to print to log
319
from bzrlib import gpg
321
gpg_strategy = gpg.GPGStrategy(None)
322
result = repo.verify_revision(rev_id, gpg_strategy)
323
if result[0] == gpg.SIGNATURE_VALID:
324
return "valid signature from {0}".format(result[1])
325
if result[0] == gpg.SIGNATURE_KEY_MISSING:
326
return "unknown key {0}".format(result[1])
327
if result[0] == gpg.SIGNATURE_NOT_VALID:
328
return "invalid signature!"
329
if result[0] == gpg.SIGNATURE_NOT_SIGNED:
330
return "no signature"
333
class LogGenerator(object):
334
"""A generator of log revisions."""
336
def iter_log_revisions(self):
337
"""Iterate over LogRevision objects.
339
:return: An iterator yielding LogRevision objects.
341
raise NotImplementedError(self.iter_log_revisions)
344
class Logger(object):
345
"""An object that generates, formats and displays a log."""
347
def __init__(self, branch, rqst):
350
:param branch: the branch to log
351
:param rqst: A dictionary specifying the query parameters.
352
See make_log_request_dict() for supported values.
355
self.rqst = _apply_log_request_defaults(rqst)
360
:param lf: The LogFormatter object to send the output to.
362
if not isinstance(lf, LogFormatter):
363
warn("not a LogFormatter instance: %r" % lf)
365
self.branch.lock_read()
367
if getattr(lf, 'begin_log', None):
370
if getattr(lf, 'end_log', None):
375
def _show_body(self, lf):
376
"""Show the main log output.
378
Subclasses may wish to override this.
380
# Tweak the LogRequest based on what the LogFormatter can handle.
381
# (There's no point generating stuff if the formatter can't display it.)
383
rqst['levels'] = lf.get_levels()
384
if not getattr(lf, 'supports_tags', False):
385
rqst['generate_tags'] = False
386
if not getattr(lf, 'supports_delta', False):
387
rqst['delta_type'] = None
388
if not getattr(lf, 'supports_diff', False):
389
rqst['diff_type'] = None
390
if not getattr(lf, 'supports_signatures', False):
391
rqst['signature'] = False
393
# Find and print the interesting revisions
394
generator = self._generator_factory(self.branch, rqst)
395
for lr in generator.iter_log_revisions():
239
396
lf.log_revision(lr)
242
if log_count >= limit:
246
def _format_diff(repo, rev, rev_id, specific_fileid):
247
if len(rev.parent_ids) == 0:
248
ancestor_id = _mod_revision.NULL_REVISION
250
ancestor_id = rev.parent_ids[0]
251
tree_1 = repo.revision_tree(ancestor_id)
252
tree_2 = repo.revision_tree(rev_id)
254
specific_files = [tree_2.id2path(specific_fileid)]
256
specific_files = None
258
diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
399
def _generator_factory(self, branch, rqst):
400
"""Make the LogGenerator object to use.
402
Subclasses may wish to override this.
404
return _DefaultLogGenerator(branch, rqst)
263
407
class _StartNotLinearAncestor(Exception):
264
408
"""Raised when a start revision is not found walking left-hand history."""
267
def _create_log_revision_iterator(branch, start_revision, end_revision,
268
direction, specific_fileid, search, generate_merge_revisions,
269
allow_single_merge_revision, generate_delta, limited_output=False):
270
"""Create a revision iterator for log.
272
:param branch: The branch being logged.
273
:param start_revision: If not None, only show revisions >= start_revision
274
:param end_revision: If not None, only show revisions <= end_revision
275
:param direction: 'reverse' (default) is latest to earliest; 'forward' is
277
:param specific_fileid: If not None, list only the commits affecting the
279
:param search: If not None, only show revisions with matching commit
281
:param generate_merge_revisions: If False, show only mainline revisions.
282
:param allow_single_merge_revision: If True, logging of a single
283
revision off the mainline is to be allowed
284
:param generate_delta: Whether to generate a delta for each revision.
285
:param limited_output: if True, the user only wants a limited result
287
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
290
start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
293
# Decide how file-ids are matched: delta-filtering vs per-file graph.
294
# Delta filtering allows revisions to be displayed incrementally
295
# though the total time is much slower for huge repositories: log -v
296
# is the *lower* performance bound. At least until the split
297
# inventory format arrives, per-file-graph needs to remain the
298
# default except in verbose mode. Delta filtering should give more
299
# accurate results (e.g. inclusion of FILE deletions) so arguably
300
# it should always be used in the future.
301
use_deltas_for_matching = specific_fileid and generate_delta
302
delayed_graph_generation = not specific_fileid and (
303
start_rev_id or end_rev_id or limited_output)
304
generate_merges = generate_merge_revisions or (specific_fileid and
305
not use_deltas_for_matching)
306
view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
307
direction, generate_merges, allow_single_merge_revision,
308
delayed_graph_generation=delayed_graph_generation)
309
search_deltas_for_fileids = None
310
if use_deltas_for_matching:
311
search_deltas_for_fileids = set([specific_fileid])
312
elif specific_fileid:
411
class _DefaultLogGenerator(LogGenerator):
412
"""The default generator of log revisions."""
414
def __init__(self, branch, rqst):
417
if rqst.get('generate_tags') and branch.supports_tags():
418
self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
420
self.rev_tag_dict = {}
422
def iter_log_revisions(self):
423
"""Iterate over LogRevision objects.
425
:return: An iterator yielding LogRevision objects.
428
levels = rqst.get('levels')
429
limit = rqst.get('limit')
430
diff_type = rqst.get('diff_type')
431
show_signature = rqst.get('signature')
433
revision_iterator = self._create_log_revision_iterator()
434
for revs in revision_iterator:
435
for (rev_id, revno, merge_depth), rev, delta in revs:
436
# 0 levels means show everything; merge_depth counts from 0
437
if levels != 0 and merge_depth >= levels:
439
if diff_type is None:
442
diff = self._format_diff(rev, rev_id, diff_type)
444
signature = format_signature_validity(rev_id,
445
self.branch.repository)
448
yield LogRevision(rev, revno, merge_depth, delta,
449
self.rev_tag_dict.get(rev_id), diff, signature)
452
if log_count >= limit:
455
def _format_diff(self, rev, rev_id, diff_type):
456
repo = self.branch.repository
457
if len(rev.parent_ids) == 0:
458
ancestor_id = _mod_revision.NULL_REVISION
460
ancestor_id = rev.parent_ids[0]
461
tree_1 = repo.revision_tree(ancestor_id)
462
tree_2 = repo.revision_tree(rev_id)
463
file_ids = self.rqst.get('specific_fileids')
464
if diff_type == 'partial' and file_ids is not None:
465
specific_files = [tree_2.id2path(id) for id in file_ids]
467
specific_files = None
469
path_encoding = get_diff_header_encoding()
470
diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
471
new_label='', path_encoding=path_encoding)
474
def _create_log_revision_iterator(self):
475
"""Create a revision iterator for log.
477
:return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
480
self.start_rev_id, self.end_rev_id = _get_revision_limits(
481
self.branch, self.rqst.get('start_revision'),
482
self.rqst.get('end_revision'))
483
if self.rqst.get('_match_using_deltas'):
484
return self._log_revision_iterator_using_delta_matching()
486
# We're using the per-file-graph algorithm. This scales really
487
# well but only makes sense if there is a single file and it's
489
file_count = len(self.rqst.get('specific_fileids'))
491
raise BzrError("illegal LogRequest: must match-using-deltas "
492
"when logging %d files" % file_count)
493
return self._log_revision_iterator_using_per_file_graph()
495
def _log_revision_iterator_using_delta_matching(self):
496
# Get the base revisions, filtering by the revision range
498
generate_merge_revisions = rqst.get('levels') != 1
499
delayed_graph_generation = not rqst.get('specific_fileids') and (
500
rqst.get('limit') or self.start_rev_id or self.end_rev_id)
501
view_revisions = _calc_view_revisions(
502
self.branch, self.start_rev_id, self.end_rev_id,
503
rqst.get('direction'),
504
generate_merge_revisions=generate_merge_revisions,
505
delayed_graph_generation=delayed_graph_generation,
506
exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
508
# Apply the other filters
509
return make_log_rev_iterator(self.branch, view_revisions,
510
rqst.get('delta_type'), rqst.get('message_search'),
511
file_ids=rqst.get('specific_fileids'),
512
direction=rqst.get('direction'))
514
def _log_revision_iterator_using_per_file_graph(self):
515
# Get the base revisions, filtering by the revision range.
516
# Note that we always generate the merge revisions because
517
# filter_revisions_touching_file_id() requires them ...
519
view_revisions = _calc_view_revisions(
520
self.branch, self.start_rev_id, self.end_rev_id,
521
rqst.get('direction'), generate_merge_revisions=True,
522
exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
313
523
if not isinstance(view_revisions, list):
314
524
view_revisions = list(view_revisions)
315
view_revisions = _filter_revisions_touching_file_id(branch,
316
specific_fileid, view_revisions,
317
include_merges=generate_merge_revisions)
318
return make_log_rev_iterator(branch, view_revisions, generate_delta,
319
search, file_ids=search_deltas_for_fileids, direction=direction)
525
view_revisions = _filter_revisions_touching_file_id(self.branch,
526
rqst.get('specific_fileids')[0], view_revisions,
527
include_merges=rqst.get('levels') != 1)
528
return make_log_rev_iterator(self.branch, view_revisions,
529
rqst.get('delta_type'), rqst.get('message_search'))
322
532
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
323
generate_merge_revisions, allow_single_merge_revision,
324
delayed_graph_generation=False):
533
generate_merge_revisions,
534
delayed_graph_generation=False,
535
exclude_common_ancestry=False,
325
537
"""Calculate the revisions to view.
327
539
:return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
328
540
a list of the same tuples.
542
if (exclude_common_ancestry and start_rev_id == end_rev_id):
543
raise errors.BzrCommandError(
544
'--exclude-common-ancestry requires two different revisions')
545
if direction not in ('reverse', 'forward'):
546
raise ValueError('invalid direction %r' % direction)
330
547
br_revno, br_rev_id = branch.last_revision_info()
331
548
if br_revno == 0:
334
# If a single revision is requested, check we can handle it
335
generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
336
(not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
337
if generate_single_revision:
338
if end_rev_id == br_rev_id:
340
return [(br_rev_id, br_revno, 0)]
342
revno = branch.revision_id_to_dotted_revno(end_rev_id)
343
if len(revno) > 1 and not allow_single_merge_revision:
344
# It's a merge revision and the log formatter is
345
# completely brain dead. This "feature" of allowing
346
# log formatters incapable of displaying dotted revnos
347
# ought to be deprecated IMNSHO. IGC 20091022
348
raise errors.BzrCommandError('Selected log formatter only'
349
' supports mainline revisions.')
350
revno_str = '.'.join(str(n) for n in revno)
351
return [(end_rev_id, revno_str, 0)]
353
# If we only want to see linear revisions, we can iterate ...
354
if not generate_merge_revisions:
355
result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
356
# If a start limit was given and it's not obviously an
357
# ancestor of the end limit, check it before outputting anything
358
if direction == 'forward' or (start_rev_id
359
and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
361
result = list(result)
362
except _StartNotLinearAncestor:
363
raise errors.BzrCommandError('Start revision not found in'
364
' left-hand history of end revision.')
365
if direction == 'forward':
366
result = reversed(list(result))
551
if (end_rev_id and start_rev_id == end_rev_id
552
and (not generate_merge_revisions
553
or not _has_merges(branch, end_rev_id))):
554
# If a single revision is requested, check we can handle it
555
iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
557
elif not generate_merge_revisions:
558
# If we only want to see linear revisions, we can iterate ...
559
iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
560
direction, exclude_common_ancestry)
561
if direction == 'forward':
562
iter_revs = reversed(iter_revs)
564
iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
565
direction, delayed_graph_generation,
566
exclude_common_ancestry)
567
if direction == 'forward':
568
iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
572
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
573
if rev_id == br_rev_id:
575
return [(br_rev_id, br_revno, 0)]
577
revno_str = _compute_revno_str(branch, rev_id)
578
return [(rev_id, revno_str, 0)]
581
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
582
exclude_common_ancestry=False):
583
result = _linear_view_revisions(
584
branch, start_rev_id, end_rev_id,
585
exclude_common_ancestry=exclude_common_ancestry)
586
# If a start limit was given and it's not obviously an
587
# ancestor of the end limit, check it before outputting anything
588
if direction == 'forward' or (start_rev_id
589
and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
591
result = list(result)
592
except _StartNotLinearAncestor:
593
raise errors.BzrCommandError('Start revision not found in'
594
' left-hand history of end revision.')
598
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
599
delayed_graph_generation,
600
exclude_common_ancestry=False):
369
601
# On large trees, generating the merge graph can take 30-60 seconds
370
602
# so we delay doing it until a merge is detected, incrementally
371
603
# returning initial (non-merge) revisions while we can.
605
# The above is only true for old formats (<= 0.92), for newer formats, a
606
# couple of seconds only should be needed to load the whole graph and the
607
# other graph operations needed are even faster than that -- vila 100201
372
608
initial_revisions = []
373
609
if delayed_graph_generation:
375
for rev_id, revno, depth in \
376
_linear_view_revisions(branch, start_rev_id, end_rev_id):
611
for rev_id, revno, depth in _linear_view_revisions(
612
branch, start_rev_id, end_rev_id, exclude_common_ancestry):
377
613
if _has_merges(branch, rev_id):
614
# The end_rev_id can be nested down somewhere. We need an
615
# explicit ancestry check. There is an ambiguity here as we
616
# may not raise _StartNotLinearAncestor for a revision that
617
# is an ancestor but not a *linear* one. But since we have
618
# loaded the graph to do the check (or calculate a dotted
619
# revno), we may as well accept to show the log... We need
620
# the check only if start_rev_id is not None as all
621
# revisions have _mod_revision.NULL_REVISION as an ancestor
623
graph = branch.repository.get_graph()
624
if (start_rev_id is not None
625
and not graph.is_ancestor(start_rev_id, end_rev_id)):
626
raise _StartNotLinearAncestor()
627
# Since we collected the revisions so far, we need to
378
629
end_rev_id = rev_id
381
632
initial_revisions.append((rev_id, revno, depth))
383
634
# No merged revisions found
384
if direction == 'reverse':
385
return initial_revisions
386
elif direction == 'forward':
387
return reversed(initial_revisions)
389
raise ValueError('invalid direction %r' % direction)
635
return initial_revisions
390
636
except _StartNotLinearAncestor:
391
637
# A merge was never detected so the lower revision limit can't
392
638
# be nested down somewhere
393
639
raise errors.BzrCommandError('Start revision not found in'
394
640
' history of end revision.')
642
# We exit the loop above because we encounter a revision with merges, from
643
# this revision, we need to switch to _graph_view_revisions.
396
645
# A log including nested merges is required. If the direction is reverse,
397
646
# we rebase the initial merge depths so that the development line is
398
647
# shown naturally, i.e. just like it is for linear logging. We can easily
1179
1489
def short_author(self, rev):
1180
name, address = config.parse_username(rev.get_apparent_authors()[0])
1490
return self.authors(rev, 'first', short=True, sep=', ')
1492
def authors(self, rev, who, short=False, sep=None):
1493
"""Generate list of authors, taking --authors option into account.
1495
The caller has to specify the name of a author list handler,
1496
as provided by the author list registry, using the ``who``
1497
argument. That name only sets a default, though: when the
1498
user selected a different author list generation using the
1499
``--authors`` command line switch, as represented by the
1500
``author_list_handler`` constructor argument, that value takes
1503
:param rev: The revision for which to generate the list of authors.
1504
:param who: Name of the default handler.
1505
:param short: Whether to shorten names to either name or address.
1506
:param sep: What separator to use for automatic concatenation.
1508
if self._author_list_handler is not None:
1509
# The user did specify --authors, which overrides the default
1510
author_list_handler = self._author_list_handler
1512
# The user didn't specify --authors, so we use the caller's default
1513
author_list_handler = author_list_registry.get(who)
1514
names = author_list_handler(rev)
1516
for i in range(len(names)):
1517
name, address = config.parse_username(names[i])
1523
names = sep.join(names)
1526
def merge_marker(self, revision):
1527
"""Get the merge marker to include in the output or '' if none."""
1528
if len(revision.rev.parent_ids) > 1:
1529
self._merge_count += 1
1185
1534
def show_properties(self, revision, indent):
1186
1535
"""Displays the custom properties returned by each registered handler.
1188
1537
If a registered handler raises an error it is propagated.
1539
for line in self.custom_properties(revision):
1540
self.to_file.write("%s%s\n" % (indent, line))
1542
def custom_properties(self, revision):
1543
"""Format the custom properties returned by each registered handler.
1545
If a registered handler raises an error it is propagated.
1547
:return: a list of formatted lines (excluding trailing newlines)
1549
lines = self._foreign_info_properties(revision)
1190
1550
for key, handler in properties_handler_registry.iteritems():
1191
for key, value in handler(revision).items():
1192
self.to_file.write(indent + key + ': ' + value + '\n')
1551
lines.extend(self._format_properties(handler(revision)))
1554
def _foreign_info_properties(self, rev):
1555
"""Custom log displayer for foreign revision identifiers.
1557
:param rev: Revision object.
1559
# Revision comes directly from a foreign repository
1560
if isinstance(rev, foreign.ForeignRevision):
1561
return self._format_properties(
1562
rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
1564
# Imported foreign revision revision ids always contain :
1565
if not ":" in rev.revision_id:
1568
# Revision was once imported from a foreign repository
1570
foreign_revid, mapping = \
1571
foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
1572
except errors.InvalidRevisionId:
1575
return self._format_properties(
1576
mapping.vcs.show_foreign_revid(foreign_revid))
1578
def _format_properties(self, properties):
1580
for key, value in properties.items():
1581
lines.append(key + ': ' + value)
1194
1584
def show_diff(self, to_file, diff, indent):
1195
1585
for l in diff.rstrip().split('\n'):
1196
1586
to_file.write(indent + '%s\n' % (l,))
1589
# Separator between revisions in long format
1590
_LONG_SEP = '-' * 60
1199
1593
class LongLogFormatter(LogFormatter):
1201
1595
supports_merge_revisions = True
1596
preferred_levels = 1
1202
1597
supports_delta = True
1203
1598
supports_tags = True
1204
1599
supports_diff = True
1600
supports_signatures = True
1602
def __init__(self, *args, **kwargs):
1603
super(LongLogFormatter, self).__init__(*args, **kwargs)
1604
if self.show_timezone == 'original':
1605
self.date_string = self._date_string_original_timezone
1607
self.date_string = self._date_string_with_timezone
1609
def _date_string_with_timezone(self, rev):
1610
return format_date(rev.timestamp, rev.timezone or 0,
1613
def _date_string_original_timezone(self, rev):
1614
return format_date_with_offset_in_original_timezone(rev.timestamp,
1206
1617
def log_revision(self, revision):
1207
1618
"""Log a revision, either merged or not."""
1208
1619
indent = ' ' * revision.merge_depth
1209
to_file = self.to_file
1210
to_file.write(indent + '-' * 60 + '\n')
1211
1621
if revision.revno is not None:
1212
to_file.write(indent + 'revno: %s\n' % (revision.revno,))
1622
lines.append('revno: %s%s' % (revision.revno,
1623
self.merge_marker(revision)))
1213
1624
if revision.tags:
1214
to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1625
lines.append('tags: %s' % (', '.join(revision.tags)))
1626
if self.show_ids or revision.revno is None:
1627
lines.append('revision-id: %s' % (revision.rev.revision_id,))
1215
1628
if self.show_ids:
1216
to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1218
1629
for parent_id in revision.rev.parent_ids:
1219
to_file.write(indent + 'parent: %s\n' % (parent_id,))
1220
self.show_properties(revision.rev, indent)
1630
lines.append('parent: %s' % (parent_id,))
1631
lines.extend(self.custom_properties(revision.rev))
1222
1633
committer = revision.rev.committer
1223
authors = revision.rev.get_apparent_authors()
1634
authors = self.authors(revision.rev, 'all')
1224
1635
if authors != [committer]:
1225
to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1226
to_file.write(indent + 'committer: %s\n' % (committer,))
1636
lines.append('author: %s' % (", ".join(authors),))
1637
lines.append('committer: %s' % (committer,))
1228
1639
branch_nick = revision.rev.properties.get('branch-nick', None)
1229
1640
if branch_nick is not None:
1230
to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
1232
date_str = format_date(revision.rev.timestamp,
1233
revision.rev.timezone or 0,
1235
to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1237
to_file.write(indent + 'message:\n')
1641
lines.append('branch nick: %s' % (branch_nick,))
1643
lines.append('timestamp: %s' % (self.date_string(revision.rev),))
1645
if revision.signature is not None:
1646
lines.append('signature: ' + revision.signature)
1648
lines.append('message:')
1238
1649
if not revision.rev.message:
1239
to_file.write(indent + ' (no message)\n')
1650
lines.append(' (no message)')
1241
1652
message = revision.rev.message.rstrip('\r\n')
1242
1653
for l in message.split('\n'):
1243
to_file.write(indent + ' %s\n' % (l,))
1654
lines.append(' %s' % (l,))
1656
# Dump the output, appending the delta and diff if requested
1657
to_file = self.to_file
1658
to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
1244
1659
if revision.delta is not None:
1245
# We don't respect delta_format for compatibility
1246
revision.delta.show(to_file, self.show_ids, indent=indent,
1660
# Use the standard status output to display changes
1661
from bzrlib.delta import report_delta
1662
report_delta(to_file, revision.delta, short_status=False,
1663
show_ids=self.show_ids, indent=indent)
1248
1664
if revision.diff is not None:
1249
1665
to_file.write(indent + 'diff:\n')
1250
1667
# Note: we explicitly don't indent the diff (relative to the
1251
1668
# revision information) so that the output can be fed to patch -p0
1252
1669
self.show_diff(self.to_exact_file, revision.diff, indent)
1670
self.to_exact_file.flush()
1672
def get_advice_separator(self):
1673
"""Get the text separating the log from the closing advice."""
1674
return '-' * 60 + '\n'
1255
1677
class ShortLogFormatter(LogFormatter):
1615
2075
lf.log_revision(lr)
1618
def _get_fileid_to_log(revision, tree, b, fp):
1619
"""Find the file-id to log for a file path in a revision range.
1621
:param revision: the revision range as parsed on the command line
1622
:param tree: the working tree, if any
1623
:param b: the branch
1624
:param fp: file path
2078
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
2079
"""Find file-ids and kinds given a list of files and a revision range.
2081
We search for files at the end of the range. If not found there,
2082
we try the start of the range.
2084
:param revisionspec_list: revision range as parsed on the command line
2085
:param file_list: the list of paths given on the command line;
2086
the first of these can be a branch location or a file path,
2087
the remainder must be file paths
2088
:param add_cleanup: When the branch returned is read locked,
2089
an unlock call will be queued to the cleanup.
2090
:return: (branch, info_list, start_rev_info, end_rev_info) where
2091
info_list is a list of (relative_path, file_id, kind) tuples where
2092
kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
2093
branch will be read-locked.
1626
if revision is None:
2095
from builtins import _get_revision_range
2096
tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
2097
add_cleanup(b.lock_read().unlock)
2098
# XXX: It's damn messy converting a list of paths to relative paths when
2099
# those paths might be deleted ones, they might be on a case-insensitive
2100
# filesystem and/or they might be in silly locations (like another branch).
2101
# For example, what should "log bzr://branch/dir/file1 file2" do? (Is
2102
# file2 implicitly in the same dir as file1 or should its directory be
2103
# taken from the current tree somehow?) For now, this solves the common
2104
# case of running log in a nested directory, assuming paths beyond the
2105
# first one haven't been deleted ...
2107
relpaths = [path] + tree.safe_relpath_files(file_list[1:])
2109
relpaths = [path] + file_list[1:]
2111
start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
2113
if relpaths in ([], [u'']):
2114
return b, [], start_rev_info, end_rev_info
2115
if start_rev_info is None and end_rev_info is None:
1627
2116
if tree is None:
1628
2117
tree = b.basis_tree()
1629
file_id = tree.path2id(fp)
1631
# go back to when time began
1633
rev1 = b.get_rev_id(1)
1634
except errors.NoSuchRevision:
1638
tree = b.repository.revision_tree(rev1)
1639
file_id = tree.path2id(fp)
2120
file_id = tree.path2id(fp)
2121
kind = _get_kind_for_file_id(tree, file_id)
2123
# go back to when time began
2126
rev1 = b.get_rev_id(1)
2127
except errors.NoSuchRevision:
2132
tree1 = b.repository.revision_tree(rev1)
2134
file_id = tree1.path2id(fp)
2135
kind = _get_kind_for_file_id(tree1, file_id)
2136
info_list.append((fp, file_id, kind))
1641
elif len(revision) == 1:
2138
elif start_rev_info == end_rev_info:
1642
2139
# One revision given - file must exist in it
1643
tree = revision[0].as_tree(b)
1644
file_id = tree.path2id(fp)
2140
tree = b.repository.revision_tree(end_rev_info.rev_id)
2142
file_id = tree.path2id(fp)
2143
kind = _get_kind_for_file_id(tree, file_id)
2144
info_list.append((fp, file_id, kind))
1646
elif len(revision) == 2:
1647
2147
# Revision range given. Get the file-id from the end tree.
1648
2148
# If that fails, try the start tree.
1649
rev_id = revision[1].as_revision_id(b)
2149
rev_id = end_rev_info.rev_id
1650
2150
if rev_id is None:
1651
2151
tree = b.basis_tree()
1653
tree = revision[1].as_tree(b)
1654
file_id = tree.path2id(fp)
1656
rev_id = revision[0].as_revision_id(b)
1658
rev1 = b.get_rev_id(1)
1659
tree = b.repository.revision_tree(rev1)
1661
tree = revision[0].as_tree(b)
2153
tree = b.repository.revision_tree(rev_id)
1662
2156
file_id = tree.path2id(fp)
2157
kind = _get_kind_for_file_id(tree, file_id)
2160
rev_id = start_rev_info.rev_id
2162
rev1 = b.get_rev_id(1)
2163
tree1 = b.repository.revision_tree(rev1)
2165
tree1 = b.repository.revision_tree(rev_id)
2166
file_id = tree1.path2id(fp)
2167
kind = _get_kind_for_file_id(tree1, file_id)
2168
info_list.append((fp, file_id, kind))
2169
return b, info_list, start_rev_info, end_rev_info
2172
def _get_kind_for_file_id(tree, file_id):
2173
"""Return the kind of a file-id or None if it doesn't exist."""
2174
if file_id is not None:
2175
return tree.kind(file_id)
1664
raise errors.BzrCommandError(
1665
'bzr log --revision takes one or two values.')
1669
2180
properties_handler_registry = registry.Registry()
1670
properties_handler_registry.register_lazy("foreign",
1672
"show_foreign_properties")
2182
# Use the properties handlers to print out bug information if available
2183
def _bugs_properties_handler(revision):
2184
if revision.properties.has_key('bugs'):
2185
bug_lines = revision.properties['bugs'].split('\n')
2186
bug_rows = [line.split(' ', 1) for line in bug_lines]
2187
fixed_bug_urls = [row[0] for row in bug_rows if
2188
len(row) > 1 and row[1] == 'fixed']
2191
return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
2194
properties_handler_registry.register('bugs_properties_handler',
2195
_bugs_properties_handler)
1675
2198
# adapters which revision ids to log are filtered. When log is called, the