dep_graph.py 10.4 KB
Newer Older
Stefan Scherfke's avatar
Stefan Scherfke committed
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
"""
Create dependency graph for all projects in a given directory:

.. code-block:: console

   $ ownconda dep-graph --out=dot ../git-projects/ ../external-recipes/ > deps.dot
   $ dot -Tsvg deps.dot > deps.svg

Create dependency graph for a given project and print them as list in
installation order:

.. code-block:: console

   $ ownconda dep-graph --requirements=scipy -o pkg ../external-recipes
   zlib
   openssl
   sqlite
   python
   openblas
   numpy
   scipy

You can use this to build a certain package and all of its requirements:

.. code-block:: console

  $ ownconda dep-graph ../external-recipes --requirements=scipy -o path | \\
  > xargs ownconda build


You can also ask why a given package is needed:

.. code-block:: console

   $ ownconda dep-graph --why=numpy ../external-recipes
   numpy
   pandas
   scipy
   h5py
   matplotlib

Get all internal dependencies of a project (ignoring third-party packages):

.. code-block:: console

   $ ownconda dep-graph --requirements=own-conda-tools --no-third-party -o dot ./ > deps.dot

You can also explicitly exclude and include packages and define the dependency
type (build, run, test).  See ``ownconda dep-graph --help`` for more
information.

"""
import fnmatch
import functools
import operator
import urllib.parse

import click
import networkx as nx

from .. import click_util, recipes


NODE = {
    'fontcolor': '0 0 .9',
    'fontsize': 18,
    'color': '0 0 0.7',
    'fillcolor': '0 0 0.7',
    'style': 'filled',
}
EDGE = {
    'color': '0 0 0.7',
    # 'style': 'solid',
    'penwidth': 2,
}
FILTERS = [
    # Try top-down and apply all filters that match a package's name:
    # ('own-*', {'color': '0.1 1 .8', 'fillcolor': '.1 1 .8'}),
]
# EXCLUDE_PKGS = {
#     'python',
#     'python >=3.5',
#     'pip',
#     'setuptools',
# }
EXCLUDE_PKGS = set()


def filter_graph(
        graph, *, requirements=None, why=None, implicit=False,
        exclude=set(), include=set(), no_third_party=False
):
    """Filter packages from *graph*.

    Remove all packages that are in the :class:`set` *exclude* and, if
    *no_third_party* is ``True``, that are external packages.  Ignore (don't
    remove) packages that are listed in the :class:`set` *include*.

    If *requirements* and *why* are both ``None``, apply no furth filtering.

    If *requirements* is not ``None``, show only the specified package and
    its direct and indirect requirements.

    If *why* is not ``None``, show only the specified packages and all packages
    that directly or indirectly depend on it.

    You can provide both, *requirements* and *why*, at the same time.  They
    don't need to specify the same package.

    """
    exclude = EXCLUDE_PKGS | set(exclude)
    if no_third_party:
        third_party = {node for node in graph if not node.startswith('own-')}
        exclude |= third_party

    # Resolve exclude and include patterns
    exclude_pkgs = set()
    for pattern in exclude:
        exclude_pkgs.update(fnmatch.filter(graph, pattern))
    include_pkgs = set()
    for pattern in include:
        include_pkgs.update(fnmatch.filter(graph, pattern))

    exclude_pkgs |= {
        node for node in graph if not graph.nodes[node].get('primary', False)
    }

    # Remove re-included pkgs from list and remove remaining nodes from graph
    exclude_pkgs -= include_pkgs
    graph.remove_nodes_from(exclude_pkgs)

    if requirements is not None or why is not None:
        # Only apply this filtering step if *requirements* or *why* are
        # specified.  We than build a list of packages to keep and remove
        # all nodes from the graph that are not in the "keep" set:
        keep = set()
        for pkg_name, func in [(requirements, find_requirements),
                               (why, find_dependents)]:
            if pkg_name is None:
                continue

            try:
                keep |= func(graph, pkg_name, implicit)
            except nx.NetworkXError:
                if pkg_name in exclude_pkgs:
                    msg = 'You have already excluded the package "{}"'
                else:
                    msg = 'The package "{}" does not exist.'
                raise click.BadParameter(msg.format(pkg_name)) from None

        remove = set(graph) - keep
        graph.remove_nodes_from(remove)


def find_requirements(graph, package, implicit):
    """Return a :class:`set` containing *package* and all of its requirements.
    """
    nodes = {package}
    to_visit = [n for n in graph.successors(package) if n not in nodes]
    while to_visit:
        node = to_visit.pop()
        nodes.add(node)

        if implicit:
            children = graph.successors(node)
            to_visit.extend([n for n in children if n not in nodes])

    return nodes


def find_dependents(graph, package, implicit):
    """Return a :class:`set` containing *package* and all of its dependents."""
    nodes = {package}
    to_visit = list(graph.predecessors(package))
    while to_visit:
        node = to_visit.pop()
        nodes.add(node)

        if implicit:
            parents = graph.predecessors(node)
            to_visit.extend([n for n in parents if n not in nodes])

    return nodes


def colorize(graph):
    n_own_nodes = len([n for n, d in graph.node.items() if d.get('primary')])
    i = 0
    for node, node_data in graph.node.items():
        if node_data.get('primary'):
            color = i / n_own_nodes
            style = {
                'color': f'{color} .8 .7',
                'fillcolor': f'{color} .8 .7',
            }
            i += 1
        else:
            style = {}

        for pattern, styles in FILTERS:
            if fnmatch.fnmatch(node, pattern):
                style.update(styles)

        node_data.update(style)


def echo_dot(graph):
    """Echo a *dot* graph for *graph*.

    *print_path* is ignored.  Instead, always the package name is used..

    """
    def attrs(attrs):
        """Format attribute dict for dot graphs."""
        attrs = ','.join(f'{k}="{v}"'
                         for k, v in attrs.items()
                         if v is not None)
        if not attrs:
            return ''

        attrs = f' [{attrs}]'
        return attrs

    click_util.echo('digraph {')
    click_util.echo(f'    node{attrs(NODE)};')
    click_util.echo(f'    edge{attrs(EDGE)};')

    for node, node_data in graph.node.items():
        click_util.echo(f'    "{node}"{attrs(node_data)};')

    for source, target in graph.edges:
        e = {
            'color': graph.node[source].get('color'),
        }
        click_util.echo(f'    "{source}"->"{target}"{attrs(e)};')

    click_util.echo('}')


def echo_pkg(graph):
    """Perform a topological sort on *graph* and print all package names."""
    items = []
    for p in recipes.sort_graph(graph):
        items.append(p)

    for item in items:
        click_util.echo(item)


def echo_path(graph):
    """Perform a topological sort on *graph* and print all project paths."""
    items = []
    for p in recipes.sort_graph(graph):
        item = graph.node[p]['path']
        # Search project root dir (strip recipe dir names):
        for path in [item] + list(item.parents):
            if path.joinpath('.gitlab-ci.yml').is_file():
                item = path
                break
        else:
            continue

        if item not in items:
            items.append(item)

    for item in items:
        click_util.echo(str(item))


def echo_project(graph):
    """Perform a topological sort on *graph* and print all GitLab project names."""
    items = []
    for p in recipes.sort_graph(graph):
        meta = graph.node[p]['meta']
        item = urllib.parse.urlparse(meta['about']['home']).path.lstrip('/')
        if item not in items:
            items.append(item)

    for item in items:
        click_util.echo(item)


OUT_FORMATS = {
    'dot': echo_dot,
    'pkg': echo_pkg,
    'path': echo_path,
    'project': echo_project,
}
DEP_TYPES = {
    'build': recipes.BUILD,
    'run': recipes.RUN,
    'test': recipes.TEST,
    'all': recipes.ALL,
}


@click.command()
@click_util.argument.recipe_root()
@click.option(
    '--dep-type',
    '-t',
    multiple=True,
    type=click.Choice(sorted(DEP_TYPES)),
    default=['all'],
    show_default=True,
    help='Only used dependencies of specified types.',
)
@click.option(
    '--ignore-versions/--no-ignore-versions',
    is_flag=True,
    default=True,
    show_default=True,
    help='Ignore version numbers of dependencies',
)
@click.option(
    '--requirements',
    '-r',
    metavar='PACKAGE',
    help=(
        'Only show the direct requirements of the given package.  '
        'Add "--implicit" to also show implicit dependencies.'
    ),
)
@click.option(
    '--why',
    '-w',
    metavar='PACKAGE',
    help=(
        'Only show the packages that directly depend on the given package.  '
        'Add "--implicit" to also show implicit dependants.'
    ),
)
@click.option(
    '--implicit',
    is_flag=True,
    default=False,
    help=(
        'Used with "-r/--requirements" and "-w/--why".  Also show implicit '
        'dependencies or dependants.'
    ),
)
@click.option(
    '--exclude',
    '-x',
    multiple=True,
    metavar='PATTERN',
    help='Exclude all packages mathing the provided Glob pattern.',
)
@click.option(
    '--include',
    '-i',
    multiple=True,
    metavar='PATTERN',
    help='Re-include previously excluded packages.',
)
@click.option(
    '--no-third-party',
    is_flag=True,
    default=False,
    help="Shortcut to \"-x '*' -i 'own-*'\"",
)
@click.option(
    '--out',
    '-o',
    type=click.Choice(sorted(OUT_FORMATS)),
    default='pkg',
    show_default=True,
    help='Output format.',
)
def cli(recipe_root, dep_type, ignore_versions, requirements, why, implicit,
        exclude, include, no_third_party, out):
    """Create a dependency graph from a number of Conda packages.

    You can specify multiple recipe roots which are all searched recursively
    for recipes.

    """
    recipe_data = recipes.load_recipes(recipe_root)
    dep_type = functools.reduce(operator.or_, (DEP_TYPES[t] for t in dep_type))
    dep_graph = recipes.get_dep_graph(recipe_data, ignore_versions, dep_type)
    filter_graph(
        dep_graph,
        requirements=requirements,
        why=why,
        implicit=implicit,
        exclude=exclude,
        include=include,
        no_third_party=no_third_party,
    )
    colorize(dep_graph)

    try:
        OUT_FORMATS[out](dep_graph)
    except nx.NetworkXException as e:
        click_util.fatal_error(str(e))