1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of git-big-picture
#
# Copyright (C) 2010 Sebastian Pipping <sebastian@pipping.org>
# Copyright (C) 2010 Julius Plenz <julius@plenz.com>
# Copyright (C) 2010-12 Valentin Haenel <valentin.haenel@gmx.de>
# Copyright (C) 2011 Yaroslav Halchenko <debian@onerussian.com>
#
# git-big-picture is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# git-big-picture is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with git-big-picture. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import copy
import optparse
import os
import re
import shlex
import subprocess
import sys
import tempfile
__version__ = '1.0.0-dev'
__docformat__ = "restructuredtext"
## settings and defaults
# format settings
GRAPHVIZ = 'graphviz'
PROCESSED = 'processed'
FORMAT = 'format'
VIEWER = 'viewer'
OUT_FILE = 'outfile'
OUTPUT_SETTINGS = [
FORMAT,
GRAPHVIZ,
PROCESSED,
VIEWER,
OUT_FILE,
]
OUTPUT_DEFAULTS = {
FORMAT: 'svg',
GRAPHVIZ: False,
PROCESSED: False,
VIEWER: False,
OUT_FILE: False,
}
# filter settings
BRANCHES = 'branches'
TAGS = 'tags'
ROOTS = 'roots'
MERGES = 'merges'
BIFURCATIONS = 'bifurcations'
FILTER_SETTINGS = [
BRANCHES,
TAGS,
ROOTS,
MERGES,
BIFURCATIONS,
]
FILTER_DEFAULTS = {
BRANCHES: True,
TAGS: True,
ROOTS: True,
MERGES: False,
BIFURCATIONS: False,
}
EXIT_CODES = {"too_many_args": 1,
"dot_not_found": 2,
"problem_with_dot": 3,
"dot_terminated_early": 4,
"not_write_to_file": 5,
"no_such_viewer": 6,
"graphviz_processed_others": 7,
"no_options": 8,
"no_git": 9,
"no_git_repo": 10,
"mutually_exclusive": 11,
}
sha1_pattern = re.compile('[0-9a-fA-F]{40}')
DEBUG = False
USAGE = "%prog OPTIONS [<repo-directory>]"
def create_parser():
parser = optparse.OptionParser(usage=USAGE, version=__version__)
format_group = optparse.OptionGroup(parser, "Output Options",
"Options to control output and format")
# output options
format_group.add_option('-f', '--format',
action='store', type='string', dest='format',
metavar='FMT', help='set output format [svg, png, ps, pdf, ...]')
format_group.add_option('-g', '--graphviz',
action='store_true', dest='graphviz',
help='output lines suitable as input for dot/graphviz')
format_group.add_option('-G', '--no-graphviz',
action='store_true', dest='no_graphviz',
help='disable dot/graphviz output')
format_group.add_option('-p', '--processed',
action='store_true', dest='processed',
help='output the dot processed, binary data')
format_group.add_option('-P', '--no-processed',
action='store_true', dest='no_processed',
help='disable binary output')
format_group.add_option('-v', '--viewer',
action='store', type='string', dest='viewer',
metavar='CMD',
help='write image to tempfile and start specified viewer')
format_group.add_option('-V', '--no-viewer',
action='store_true', dest='no_viewer',
help='disable starting viewer')
format_group.add_option('-o', '--outfile',
action='store', type='string', dest='outfile',
metavar='FILE', help='write image to specified file')
format_group.add_option('-O', '--no-outfile',
action='store_true', dest='no_outfile',
help='disable writing image to file')
parser.add_option_group(format_group)
filter_group = optparse.OptionGroup(parser, "Filter Options",
"Options to control commit/ref selection")
# commit/ref selection -- filtering options
filter_group.add_option('-a', '--all',
action='store_true', dest='all_commits',
help='include all commits')
filter_group.add_option('-b', '--branches',
action='store_true', dest='branches',
help='show commits pointed to by branches')
filter_group.add_option('-B', '--no-branches',
action='store_true', dest='no_branches',
help='do not show commits pointed to by branches')
filter_group.add_option('-t', '--tags',
action='store_true', dest='tags',
help='show commits pointed to by tags')
filter_group.add_option('-T', '--no-tags',
action='store_true', dest='no_tags',
help='do not show commits pointed to by tags')
filter_group.add_option('-r', '--roots',
action='store_true', dest='roots',
help='show root commits')
filter_group.add_option('-R', '--no-roots',
action='store_true', dest='no_roots',
help='do not show root commits')
filter_group.add_option('-m', '--merges',
action='store_true', dest='merges',
help='include merge commits')
filter_group.add_option('-M', '--no-merges',
action='store_true', dest='no_merges',
help='do not include merge commits')
filter_group.add_option('-i', '--bifurcations',
action='store_true', dest='bifurcations',
help='include bifurcation commits')
filter_group.add_option('-I', '--no-bifurcations',
action='store_true', dest='no_bifurcations',
help='do not include bifurcation commits')
parser.add_option_group(filter_group)
# miscellaneous options
parser.add_option('--pstats',
action='store', type='string', dest='pstats_outfile',
metavar='FILE',
help='run cProfile profiler writing pstats output to FILE')
parser.add_option('-d', '--debug',
action='store_true', dest='debug',
help='activate debug output')
return parser
PARSER = create_parser()
def barf(message, exit_code):
""" Abort execution with error message and exit code.
Parameters
----------
message : string
error message
exit_code : int
exit code for program
"""
sys.stderr.write('fatal: %s\n' % message)
sys.exit(exit_code)
def warn(message):
""" Print a warning message.
Parameters
----------
message : string
the warning
"""
sys.stderr.write('warning: %s\n' % message)
def debug(message):
""" Print a debug message.
Parameters
----------
message : string
the debug message
"""
if DEBUG:
sys.stdout.write('debug: %s\n' % message)
def parse_variable_args(args):
""" Parse arguments and get repo_dir.
Parameters
----------
args : list
arguments given on command line
Returns
-------
repo_dir : path
path to the repo_dir
"""
if len(args) > 1:
barf('Too many arguments: %s' % args, EXIT_CODES["too_many_args"])
return args[0] if len(args) == 1 else os.getcwd()
def run_dot(output_format, dot_file_lines):
""" Run the 'dot' utility.
Parameters
----------
output_format : string
format of output [svg, png, ps, pdf, ...]
dot_file_lines : list of strings
graphviz input lines
Returns
-------
Raw output from 'dot' utility
"""
try:
p = subprocess.Popen(['dot', '-T' + output_format],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError as e:
if e.errno == 2:
barf("'dot' not found! Please install the Graphviz utility.",
EXIT_CODES["dot_not_found"])
else:
barf("A problem occured calling 'dot -T%s'" % output_format,
EXIT_CODES["problem_with_dot"])
# send dot input, automatically receive and store output and error
out, err = p.communicate(input='\n'.join(dot_file_lines))
if p.returncode != 0:
barf("'dot' terminated prematurely with error code %d;\n"
"probably you specified an invalid format, see 'man dot'.\n"
"The error from 'dot' was:\n>>>"
% p.returncode + err, EXIT_CODES["dot_terminated_early"])
return out
def write_to_file(output_file, dot_output):
""" Write the output from the 'dot' utility to file.
Parameters
----------
output_file : string
filename of output file
dot_output : list of strings
raw output from the 'dot' utility
"""
try:
f = open(output_file, 'w+b')
except IOError as e:
barf("Could not open file '%s':\n>>>%s"
% (output_file, e),
EXIT_CODES["not_write_to_file"])
f.write(dot_output)
f.flush()
os.fsync(f.fileno())
f.close()
def show_in_viewer(output_file, viewer):
""" Show the output of 'dot' utility in a viewer.
If 'output' is a file, open viewer on that file, else assume its the raw
output from the 'dot' utility, write that to a temporary file, and open
viewer on that.
Parameters
----------
output_file : str
name of the output file
viewer : string
name of the viewer to use
"""
try:
subprocess.call([viewer, output_file])
except OSError as e:
barf("Error calling viewer: '%s':\n>>>%s" % (viewer, e),
EXIT_CODES["no_such_viewer"])
def guess_format_from_filename(output_file):
""" Guess the output format from the filename.
Parameters
----------
output_file : string
filename of the output file
Returns
-------
has_suffix : boolean
True if the filename had a suffix, False otherwise
guess:
the format guess if the filename has a suffix and None otherwise
"""
if '.' in output_file:
return True, opts.outfile.split('.')[-1]
else:
return False, None
def parse_output_options(opts):
cmdline_settings = {}
for setting in OUTPUT_SETTINGS[1:]:
positive, negative = getattr(opts, setting), getattr(opts, 'no_' + setting)
if positive is not None and negative is not None:
barf("'%s' and '%s' are mutually exclusive" %
('--' + setting, '--no-' + setting),
EXIT_CODES['mutually_exclusive'])
if positive is not None:
cmdline_settings[setting] = positive
elif negative is not None:
cmdline_settings[setting] = False
else:
cmdline_settings[setting] = None
val = getattr(opts, FORMAT)
cmdline_settings[FORMAT] = val if val is not None else None
return cmdline_settings
def parse_filter_options(opts):
""" Extract and check the filtering options from the command line 'opts'.
Checks that not both the option and it's negation were found. The return
dict contains one entry for each setting. This entry can be True to signal
the option was found, False to signal the negation was found and None to
signal that neither was found.
Parameters
----------
opts : dict
options dict from cmdline
Returns
-------
cmdline_settings : dict
the settings dict
"""
cmdline_settings = {}
for setting in FILTER_SETTINGS:
positive, negative = getattr(opts, setting), getattr(opts, 'no_' + setting)
if positive is not None and negative is not None:
barf("'%s' and '%s' are mutually exclusive" %
('--' + setting, '--no-' + setting),
EXIT_CODES['mutually_exclusive'])
elif positive is not None:
cmdline_settings[setting] = True
elif negative is not None:
cmdline_settings[setting] = False
else:
cmdline_settings[setting] = None
return cmdline_settings
def set_settings(settings, defaults, conf, cli):
""" Extract the value for setting in order.
If any of the 'containers' are None, it will be skipped.
Parameters
----------
setting : list of str
the settings to look for
defaults : dict
defaults
conf : dict
configuration file
cli : dict like
command line settings
Returns
-------
val : str
an appropriate value for setting
"""
order = [('defaults', defaults),
('conf file', conf),
('command line args', cli)]
output = {}
for setting in settings:
prev, val, prev_val = None, None, None
for desc, container in order:
if container is None:
continue
if container[setting] is not None:
prev_val, val = val, container[setting]
if prev_val is not None:
debug("Value for '%s' found in '%s', overrides setting '%s' from '%s': '%s'"
% (setting, desc, prev_val, prev, val))
else:
debug("Value for '%s' found in '%s': '%s'"
% (setting, desc, val))
prev = desc
if val is None:
debug("No value for '%s' found anywhere" % setting)
output[setting] = val
return output
def get_command_output(command_list, cwd=None, git_env=None):
""" Execute arbitrary commands.
Parameters
----------
command_list : list of strings
the command and its arguments
cwd : string
current working directory to execute command in
git_env : dict
the git environment, if any
Returns
-------
output : string
the raw output of the command executed
"""
p = subprocess.Popen(command_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=git_env, cwd=cwd)
load = p.stdout.read()
p.wait()
if p.returncode:
err = p.stderr.read()
err = '\n'.join(('> ' + e) for e in err.split('\n'))
raise Exception('Stderr:\n%s\nReturn code %d from command "%s"'
% (err, p.returncode, ' '.join(command_list)))
return load
class Git(object):
def __init__(self, repo_dir):
self.repo_dir = repo_dir
# under the assumption that if git rev-parse fails
# it really is not a git repo
try:
self('git rev-parse')
except Exception:
barf("'%s' is probably not a Git repository" % self.repo_dir,
EXIT_CODES['no_git_repo'])
def __call__(self, command):
return get_command_output(shlex.split(command),
cwd=self.repo_dir).splitlines()
def config(self, settings):
config_settings = {}
for setting in settings:
try:
val = self('git config big-picture.%s' % setting)[0]
except Exception:
val = None
if val is None:
config_settings[setting] = None
elif val.lower() in ['1', 'yes', 'true', 'on']:
config_settings[setting] = True
elif val.lower() in ['0', 'no', 'false', 'off']:
config_settings[setting] = False
else:
config_settings[setting] = val
return config_settings
def get_mappings(self):
""" Get mappings for all refs.
This is implemented using a single call to 'git for-each-ref'. Note
that it can handle non commit tags too and returns these
Returns
-------
(lbranches, rbranches, abranches), (tags, ctags, nctags)
lbranches : dict mapping strings to sets of strings
mapping of commit sha1s to local branch names
rbranches : dict mapping strings to sets of strings
mapping of commit sha1s to remote branch names
abranches : dict mapping strings to sets of strings
mapping of commit sha1s to all branch names
tags : dict mapping strings to sets of strings
mapping of object sha1s to tag names
ctags : dict mapping sha1s to sets of strings
mapping of commits sha1s to tag names
nctags : dict mapping sha1s to sets of strings
mapping of non-commit sha1s to sets of strings
"""
output = self("git for-each-ref --format=\"['%(objectname)', '%(*objectname)', '%(objecttype)', '%(refname)']\"")
lbranch_prefix = 'refs/heads/'
rbranch_prefix = 'refs/remotes/'
tag_prefix = 'refs/tags/'
lbranches, rbranches, abranches = {}, {}, {}
tags, ctags, nctags = {}, {}, {}
def add_to_dict(dic, sha1, name):
dic.setdefault(sha1, set()).add(name)
for ref_info in output:
sha1, tag_sha1, ref_type, name = eval(ref_info)
if ref_type not in ['commit', 'tag']:
continue
elif name.startswith(lbranch_prefix):
add_to_dict(lbranches, sha1, name.replace(lbranch_prefix, ''))
add_to_dict(abranches, sha1, name.replace(lbranch_prefix, ''))
elif name.startswith(rbranch_prefix):
add_to_dict(rbranches, sha1, name.replace(rbranch_prefix, ''))
add_to_dict(abranches, sha1, name.replace(rbranch_prefix, ''))
elif name.startswith(tag_prefix):
# recusively dereference until we find a non-tag object
sha1 = self('git rev-parse %s^{}' % name)[0]
# determine object type and to respective dict
obj_type = self('git cat-file -t %s' % sha1)[0]
if obj_type in ['blob', 'tree']:
add_to_dict(nctags, sha1, name.replace(tag_prefix, ''))
else:
add_to_dict(ctags, sha1, name.replace(tag_prefix, ''))
add_to_dict(tags, sha1, name.replace(tag_prefix, ''))
return (lbranches, rbranches, abranches), (tags, ctags, nctags)
def get_parent_map(self):
""" Get a mapping of children to parents.
Returns
-------
parents : dict mapping strings to sets of strings
mapping of children sha1s to parents sha1
"""
parents = {}
lines = self('git rev-list --all --parents')
for line in lines:
sha_ones = [e.group(0) for e in re.finditer(sha1_pattern, line)]
count = len(sha_ones)
if count > 1:
parents[sha_ones[0]] = set(sha_ones[1:])
elif count == 1:
parents[sha_ones[0]] = set()
return parents
def graph_factory(repo_dir):
""" Create a CommitGraph object from a git_dir. """
git = Git(repo_dir)
(lb, rb, ab), (tags, ctags, nctags) = git.get_mappings()
return CommitGraph(git.get_parent_map(), ab, tags, git=git)
class CommitGraph(object):
""" Directed Acyclic Graph (DAG) git repository.
Parameters
----------
parent_map : dict mapping SHA1s to list of SHA1s
the parent map
branch_dict : dict mapping SHA1s to list of strings
the branches
tag_dict : dict mapping SHA1s to list of strings
the tags
Properties
----------
roots : list of SHA1s
all root commits (the ones with no parents)
merges : list of SHA1s
all merge commits (the ones with multiple parents)
bifurcations : list SHA1s
all bifurcation commits (the ones with multiple children)
Attributes
----------
parents : dict mapping SHA1s to list of SHA1s
the parent map
children : dict mapping SHA1s to list of SHA1s
the child map
branches : dict mapping SHA1s to list of strings
the branches
tags : dict mapping SHA1s to list of strings
tags
git : Git
interface to dispatch commands to this repo
"""
def __init__(self, parent_map, branch_dict, tag_dict, git=None):
self.parents = parent_map
self.branches = branch_dict
self.tags = tag_dict
self.dotdot = set()
self.git = git
self.children = {}
self._calculate_child_mapping()
self._verify_child_mapping()
def _has_label(self, sha_one):
""" Check if a sha1 is pointed to by a ref.
Parameters
----------
sha_one : string
"""
return sha_one in self.branches \
or sha_one in self.tags
def _calculate_child_mapping(self):
""" Populate the self.children dict, using self.parents. """
for sha_one, parent_sha_ones in self.parents.items():
for p in parent_sha_ones:
if p not in self.children:
self.children[p] = set()
self.children[p].add(sha_one)
if sha_one not in self.children:
self.children[sha_one] = set()
def _verify_child_mapping(self):
""" Ensure that self.parents and self.children represent the same DAG.
"""
for sha_one, pars in self.parents.items():
for p in pars:
for c in self.children[p]:
assert(p in self.parents[c])
for sha_one, chs in self.children.items():
for c in chs:
for p in self.parents[c]:
assert(c in self.children[p])
@property
def roots(self):
""" Find all root commits. """
return [sha for sha, parents in self.parents.items() if not parents]
@property
def merges(self):
""" Find all merge commits. """
return [sha for sha, parents in self.parents.items()
if len(parents) > 1]
@property
def bifurcations(self):
""" Find all bifurcations. """
return [sha for sha, children in self.children.items()
if len(children) > 1]
def filter(self,
branches=FILTER_DEFAULTS[BRANCHES],
tags=FILTER_DEFAULTS[TAGS],
roots=FILTER_DEFAULTS[ROOTS],
merges=FILTER_DEFAULTS[MERGES],
bifurcations=FILTER_DEFAULTS[BIFURCATIONS],
additional=None):
""" Filter the commit graph.
Remove, or 'filter' the unwanted commits from the DAG. This will modify
self.parents and when done re-calculate self.children. Keyword
arguments can be used to specify 'interesting' commits
Generate a reachability graph for 'interesting' commits. This will
generate a graph of all interesting commits, with edges pointing to all
reachable 'interesting' parents.
Parameters
----------
branches : bool
include commits being pointed to by branches
tags : bool
include commits being pointed to by tags
roots : bool
include root commits
merges : bool
include merge commits
bifurcations : bool
include bifurcation commits
additional : list of SHA1 sums
any additional commits to include
Returns
-------
commit_graph : CommitGraph
the filtered graph
"""
interesting = []
if branches:
interesting.extend(self.branches.keys())
if tags:
interesting.extend(self.tags.keys())
if roots:
interesting.extend(self.roots)
if merges:
interesting.extend(self.merges)
if bifurcations:
interesting.extend(self.bifurcations)
if additional:
interesting.extend(additional)
reachable_interesting_parents = dict()
# for everything that we are interested in
for commit_i in interesting:
# Handle tags pointing to non-commits
if commit_i in self.parents:
to_visit = list(self.parents[commit_i])
else:
to_visit = list()
# create the set of seen commits
seen = set()
# initialise the parents for this commit_i
reachable_interesting_parents[commit_i] = set()
# iterate through to_visit list, i.e. go searching in the graph
for commit_j in to_visit:
# we have already been here
if commit_j in seen:
continue
else:
seen.add(commit_j)
if commit_j in interesting:
# is interesting, add and stop
reachable_interesting_parents[commit_i].add(commit_j)
else:
# is not interesting, keep searching
to_visit.extend(self.parents[commit_j])
return CommitGraph(reachable_interesting_parents,
copy.deepcopy(self.branches),
copy.deepcopy(self.tags))
def _minimal_sha_one_digits(self):
""" Calculate the minimal number of sha1 digits required to represent
all commits unambiguously. """
key_count = len(self.parents)
for digit_count in xrange(7, 40):
if len(set(e[0:digit_count] for e in self.parents.keys())) == key_count:
return digit_count
return 40
def _generate_dot_file(self, sha_ones_on_labels, sha_one_digits=None):
""" Generate graphviz input.
Parameters
----------
sha_ones_on_labels : boolean
if True show sha1 (or minimal) on labels in addition to ref names
sha_one_digits : int
number of digits to use for showing sha1
Returns
-------
dot_file_lines : list of strings
lines of the graphviz input
"""
def format_sha_one(sha_one):
""" Shorten sha1 if required. """
if (sha_one_digits is None) or (sha_one_digits == 40):
return sha_one
else:
return sha_one[0:sha_one_digits]
def label_gen():
keys = set(self.branches.keys()).union(set(self.tags.keys()))
for k in (k for k in keys
if k in self.parents or k in self.children):
labels = []
case = 0
if k in self.tags:
case = case + 1
map(labels.append, sorted(self.tags[k]))
if k in self.branches:
case = case + 2
map(labels.append, sorted(self.branches[k]))
# http://www.graphviz.org/doc/info/colors.html
color = "/pastel13/%d" % case
yield (k, labels, color)
dot_file_lines = ['digraph {']
for sha_one, labels, color in label_gen():
dot_file_lines.append('\t"%(ref)s"[label="%(label)s", color="%(color)s", style=filled];' % {
'ref':sha_one,
'label':'\\n'.join(labels \
+ (sha_ones_on_labels and [format_sha_one(sha_one),] or list())),
'color':color})
for sha_one in self.dotdot:
dot_file_lines.append('\t"%(ref)s"[label="..."];' % {'ref':sha_one})
if (sha_one_digits is not None) and (sha_one_digits != 40):
for sha_one in (e for e in self.parents.keys() if not (self._has_label(e) or e in self.dotdot)):
dot_file_lines.append('\t"%(ref)s"[label="%(label)s"];' % {
'ref':sha_one,
'label':format_sha_one(sha_one)})
for child, self.parents in self.parents.items():
for p in self.parents:
dot_file_lines.append('\t"%(source)s" -> "%(target)s";' % {'source':child, 'target':p})
dot_file_lines.append('}')
return dot_file_lines
def main(opts, args):
repo_dir = parse_variable_args(args)
debug("The Git repository is at: '%s'" % repo_dir)
graph = graph_factory(repo_dir)
output_settings = set_settings(OUTPUT_SETTINGS,
OUTPUT_DEFAULTS,
graph.git.config(OUTPUT_SETTINGS),
parse_output_options(opts))
filter_settings = set_settings(FILTER_SETTINGS,
FILTER_DEFAULTS,
graph.git.config(FILTER_SETTINGS),
parse_filter_options(opts))
if opts.all_commits:
sha_one_digits = graph._minimal_sha_one_digits()
else:
sha_one_digits = None
graph = graph.filter(**filter_settings)
sha_one_digits = graph._minimal_sha_one_digits()
dot_file_lines = graph._generate_dot_file(sha_ones_on_labels=opts.all_commits, sha_one_digits=sha_one_digits)
if (output_settings[GRAPHVIZ] and output_settings[PROCESSED]):
barf("Options '-g | --graphviz' and '-p | --processed' " +
"are mutually exclusive.",
EXIT_CODES["graphviz_processed_others"])
elif (output_settings[GRAPHVIZ] or output_settings[PROCESSED]) and any([
output_settings[VIEWER],
output_settings[OUT_FILE]]):
barf("Options '-g | --graphviz' and '-p | --processed' " +
"are incompatible with other output options.",
EXIT_CODES["graphviz_processed_others"])
elif not any([
output_settings[GRAPHVIZ],
output_settings[PROCESSED],
output_settings[VIEWER],
output_settings[OUT_FILE]]):
barf("Must provide an output option. Try '-h' for more information",
EXIT_CODES["no_options"])
# if plain just print dot input to stdout
if output_settings[GRAPHVIZ]:
debug('Will now print dot format')
for line in dot_file_lines:
print(line)
return
# check for format mismatch between -f and -o
if output_settings[FORMAT] and output_settings[OUT_FILE]:
(has_suffix, guess) = guess_format_from_filename(
output_settings[OUT_FILE])
if output_settings[FORMAT] != guess and guess is not None:
debug("Format mismatch: '%s'(-f|--format or default)"
"vs. '%s'(filename), will use: "
"'%s'" % (output_settings[FORMAT], guess, guess))
output_settings[FORMAT] = guess
if guess is None:
warn('Filename had no suffix, using format: %s' %
output_settings[FORMAT])
output_settings[OUT_FILE] += '.' + output_settings[FORMAT]
# run the 'dot' utility
dot_output = run_dot(output_settings[FORMAT], dot_file_lines)
# create outfile and possibly view that or a temporary file in viewer
if output_settings[VIEWER] or output_settings[OUT_FILE]:
# no output file requested, create a temporary one
if not output_settings[OUT_FILE]:
output_settings[OUT_FILE] = tempfile.NamedTemporaryFile(
prefix='git-big-picture').name
debug("Created temp file: '%s'" % output_settings[OUT_FILE])
debug("Writing to file: '%s'" % output_settings[OUT_FILE])
write_to_file(output_settings[OUT_FILE], dot_output)
if output_settings[VIEWER]:
debug("Will now open file in viewer: '%s'" %
output_settings[VIEWER])
show_in_viewer(output_settings[OUT_FILE], output_settings[VIEWER])
elif output_settings[PROCESSED]:
debug("Will now print dot processed output in format: '%s'" %
output_settings[FORMAT])
print(dot_output)
if __name__ == '__main__':
opts, args = PARSER.parse_args()
if opts.debug is not None:
DEBUG = True
debug('Activate debug')
try:
get_command_output(['git', '--help'])
except Exception as e:
barf("git is either not installed or not on your $PATH:\n>>>%s" % e,
EXIT_CODES["no_git"])
if opts.pstats_outfile is not None:
import cProfile
debug("Running in profiler, output is: '%s'" % opts.pstats_outfile)
cProfile.run('main(opts, args)', opts.pstats_outfile)
else:
main(opts, args)
|