| 1 | import pathlib |
| 2 | import pygraphviz |
| 3 | |
| 4 | from import_deps import PyModule, ModuleSet |
| 5 | |
| 6 | |
| 7 | DOIT_CONFIG = { |
| 8 | 'default_tasks': ['imports', 'dot', 'draw'], |
| 9 | } |
| 10 | |
| 11 | |
| 12 | base_path = pathlib.Path('projects/requests/requests') |
| 13 | PKG_MODULES = ModuleSet(base_path.glob('**/*.py')) |
| 14 | |
| 15 | |
| 16 | def get_imports(pkg_modules, module_path): |
| 17 | module = pkg_modules.by_path[module_path] |
| 18 | imports = pkg_modules.get_imports(module, return_fqn=True) |
| 19 | return {'modules': list(sorted(imports))} |
| 20 | |
| 21 | |
| 22 | def task_imports(): |
| 23 | """find imports from a python module""" |
| 24 | for name, module in PKG_MODULES.by_name.items(): |
| 25 | yield { |
| 26 | 'name': name, |
| 27 | 'file_dep': [module.path], |
| 28 | 'actions': [(get_imports, (PKG_MODULES, module.path))], |
| 29 | } |
| 30 | |
| 31 | |
| 32 | def print_imports(modules): |
| 33 | print('\n'.join(modules)) |
| 34 | |
| 35 | def task_print(): |
| 36 | """print on stdout list of direct module imports""" |
| 37 | for name, module in PKG_MODULES.by_name.items(): |
| 38 | yield { |
| 39 | 'name': name, |
| 40 | 'actions': [print_imports], |
| 41 | 'getargs': {'modules': ('imports:{}'.format(name), 'modules')}, |
| 42 | 'uptodate': [False], |
| 43 | 'verbosity': 2, |
| 44 | } |
| 45 | |
| 46 | |
| 47 | def module_to_dot(imports, targets): |
| 48 | graph = pygraphviz.AGraph(strict=False, directed=True) |
| 49 | graph.node_attr['color'] = 'lightblue2' |
| 50 | graph.node_attr['style'] = 'filled' |
| 51 | for source, sinks in imports.items(): |
| 52 | for sink in sinks: |
| 53 | graph.add_edge(source, sink) |
| 54 | graph.write(targets[0]) |
| 55 | |
| 56 | def task_dot(): |
| 57 | """generate a graphviz's dot graph from module imports""" |
| 58 | return { |
| 59 | 'targets': ['requests.dot'], |
| 60 | 'actions': [module_to_dot], |
| 61 | 'getargs': {'imports': ('imports', 'modules')}, |
| 62 | 'clean': True, |
| 63 | } |
| 64 | |
| 65 | |
| 66 | def task_draw(): |
| 67 | """generate image from a dot file""" |
| 68 | return { |
| 69 | 'file_dep': ['requests.dot'], |
| 70 | 'targets': ['requests.png'], |
| 71 | 'actions': ['dot -Tpng %(dependencies)s -o %(targets)s'], |
| 72 | 'clean': True, |
| 73 | } |