PKniM&wily/__init__.py""" A Python application for tracking, reporting on timing and complexity in tests and applications. """ import colorlog import datetime __version__ = "1.0.0" _handler = colorlog.StreamHandler() _handler.setFormatter(colorlog.ColoredFormatter("%(log_color)s%(message)s")) logger = colorlog.getLogger(__name__) logger.addHandler(_handler) """ Max number of characters of the Git commit to print """ MAX_MESSAGE_WIDTH = 50 def format_date(timestamp): """ Reusable timestamp -> date """ return datetime.date.fromtimestamp(timestamp).isoformat() def format_datetime(timestamp): """ Reusable timestamp -> datetime """ return datetime.datetime.fromtimestamp(timestamp).isoformat() def format_revision(sha): """ Return a shorter git sha """ return sha[:7] PKAiiM^wily/__main__.py# -*- coding: UTF-8 -*- """ Main command line """ import os.path import click from wily import logger from wily.cache import exists, get_default_metrics from wily.config import load as load_config from wily.config import DEFAULT_CONFIG_PATH, DEFAULT_CACHE_PATH from wily.archivers import resolve_archiver from wily.operators import resolve_operators @click.group() @click.option( "--debug/--no-debug", default=False, help="Print debug information, used for development", ) @click.option( "--config", default=DEFAULT_CONFIG_PATH, help="Path to configuration file, defaults to wily.cfg", ) @click.option( "-p", "--path", type=click.Path(resolve_path=True), default=".", help="Root path to the project folder to scan", ) @click.pass_context def cli(ctx, debug, config, path): """\U0001F98A Inspect and search through the complexity of your source code. To get started, build an index of your source code: $ wily build Then explore basic metrics with: $ wily report You can also graph specific metrics in a browser with: $ wily graph """ ctx.ensure_object(dict) ctx.obj["DEBUG"] = debug if debug: logger.setLevel("DEBUG") else: logger.setLevel("INFO") ctx.obj["CONFIG"] = load_config(config) if path: logger.debug(f"Fixing path to {path}") ctx.obj["CONFIG"].path = path ctx.obj["CONFIG"].cache_path = os.path.join(path, DEFAULT_CACHE_PATH) logger.debug(f"Loaded configuration from {config}") @cli.command() @click.option( "-h", "--max-revisions", default=None, type=click.INT, help="The maximum number of historical commits to archive", ) @click.argument("targets", type=click.Path(resolve_path=True), nargs=-1) @click.option( "-o", "--operators", type=click.STRING, help="List of operators, separated by commas", ) @click.pass_context def build(ctx, max_revisions, targets, operators): """Build the wily cache""" config = ctx.obj["CONFIG"] from wily.commands.build import build if max_revisions: logger.debug(f"Fixing revisions to {max_revisions}") config.max_revisions = max_revisions if operators: logger.debug(f"Fixing operators to {operators}") config.operators = operators.strip().split(",") logger.debug(f"Fixing targets to {targets}") config.targets = targets build( config=config, archiver=resolve_archiver(config.archiver), operators=resolve_operators(config.operators), ) logger.info( "Completed building wily history, run `wily report ` or `wily index` to see more." ) @cli.command() @click.pass_context @click.option("--message/--no-message", default=False, help="Include revision message") def index(ctx, message): """Show the history archive in the .wily/ folder.""" config = ctx.obj["CONFIG"] if not exists(config): logger.error(f"Could not locate wily cache. Run `wily build` first.") exit(-1) from wily.commands.index import index index(config=config, include_message=message) @cli.command() @click.argument("file", type=click.Path(resolve_path=False)) @click.option( "--metrics", default=None, help="comma-seperated list of metrics, see list-metrics for choices", ) @click.option("-n", "--number", help="Number of items to show", type=click.INT) @click.option("--message/--no-message", default=False, help="Include revision message") @click.pass_context def report(ctx, file, metrics, number, message): """Show metrics for a given file.""" config = ctx.obj["CONFIG"] if not exists(config): logger.error(f"Could not locate wily cache. Run `wily build ` first.") exit(-1) if not metrics: metrics = get_default_metrics(config) logger.info(f"Using default metrics {metrics}") else: metrics = metrics.split(",") from wily.commands.report import report logger.debug(f"Running report on {file} for metric {metrics}") report(config=config, path=file, metrics=metrics, n=number, include_message=message) @cli.command() @click.argument("files", type=click.Path(resolve_path=False)) @click.argument("metric") @click.pass_context def graph(ctx, files, metric): """Graph a specific metric for a given file.""" config = ctx.obj["CONFIG"] if not exists(config): logger.error(f"Could not locate wily cache. Run `wily build ` first.") exit(-1) from wily.commands.graph import graph logger.debug(f"Running report on {files} for metric {metric}") graph(config=config, paths=[files], metric=metric) @cli.command() @click.option("-y/-p", "--yes/--prompt", default=False, help="Skip prompt") @click.pass_context def clean(ctx, yes): """Clear the .wily/ folder.""" config = ctx.obj["CONFIG"] if not exists(config): logger.error(f"Could not locate wily cache.") exit(-1) if not yes: p = input("Are you sure you want to delete wily cache? [y/N]") if p.lower() != "y": exit(0) from wily.cache import clean clean(config) @cli.command("list-metrics") @click.pass_context def list_metrics(ctx): """List the available metrics""" config = ctx.obj["CONFIG"] if not exists(config): logger.error(f"Could not locate wily cache.") exit(-1) from wily.commands.list_metrics import list_metrics list_metrics() if __name__ == "__main__": cli() PKAiiMEE wily/cache.py""" A module for working with the .wily/ cache directory This API is not intended to be public and should not be consumed directly. The API in this module is for archivers and commands to work with the local cache TODO: Version .wily/ cache folders? """ import shutil import pathlib import os.path import json from wily.archivers import ALL_ARCHIVERS from wily.operators import resolve_operator from wily import logger def exists(config): """ Check whether the .wily/ directory exists :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean`` """ return ( pathlib.Path(config.cache_path).exists() and pathlib.Path(config.cache_path).is_dir() ) def create(config): """ Create a wily cache :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: The path to the cache :rtype: ``str`` """ if exists(config): logger.debug("Wily cache exists, skipping") return config.cache_path logger.debug(f"Creating wily cache {config.cache_path}") pathlib.Path(config.cache_path).mkdir() return config.cache_path def clean(config): """ Delete a wily cache :param config: The configuration :type config: :class:`wily.config.WilyConfig` """ if not exists(config): logger.debug("Wily cache does not exist, skipping") return shutil.rmtree(config.cache_path) logger.debug("Deleted wily cache") def store(config, archiver, revision, stats): """ Store a revision record within an archiver folder :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :param revision: The revision ID :type revision: ``str`` :param stats: The collected data :type stats: ``dict`` :return: The absolute path to the created file :rtype: ``str`` :rtype: `pathlib.Path` """ root = pathlib.Path(config.cache_path) / archiver.name if not root.exists(): logger.debug("Creating wily cache") root.mkdir() # fix absolute path references. if config.path != ".": for operator, operator_data in list(stats["operator_data"].items()): new_operator_data = operator_data.copy() for k, v in list(operator_data.items()): new_key = os.path.relpath(str(k), str(config.path)) del new_operator_data[k] new_operator_data[new_key] = v del stats["operator_data"][operator] stats["operator_data"][operator] = new_operator_data logger.debug(f"Creating {revision.key} output") filename = root / (revision.key + ".json") if filename.exists(): raise RuntimeError(f"File {filename} already exists, index may be corrupt.") with open(filename, "w") as out: out.write(json.dumps(stats, indent=2)) return filename def store_index(config, archiver, index): """ Store an archiver's index record for faster search :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :param index: The archiver index record :type index: ``dict`` :rtype: `pathlib.Path` """ root = pathlib.Path(config.cache_path) / archiver.name if not root.exists(): root.mkdir() logger.debug("Created archiver directory") filename = root / "index.json" with open(filename, "w") as out: out.write(json.dumps(index, indent=2)) logger.debug(f"Created index output") return filename def list_archivers(config): """ List the names of archivers with data :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: A list of archiver names :rtype: ``list`` of ``str`` """ root = pathlib.Path(config.cache_path) result = [] for archiver in ALL_ARCHIVERS: if (root / archiver.name).exists(): result.append(archiver.name) return result def get_default_metrics(config): """ Get the default metrics for a configuration :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Return the list of default metrics in this index :rtype: ``list`` of ``str`` """ archivers = list_archivers(config) default_metrics = [] for archiver in archivers: index = get_index(config, archiver) if len(index) == 0: logger.warning("No records found in the index, no metrics available") return [] operators = index[0]["operators"] for operator in operators.split(","): o = resolve_operator(operator) if o.cls.default_metric_index is not None: metric = o.cls.metrics[o.cls.default_metric_index] default_metrics.append("{0}.{1}".format(o.cls.name, metric.name)) return default_metrics def has_index(config, archiver): """ Does this archiver have an index file? :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :return: the exist :rtype: ``bool`` """ root = pathlib.Path(config.cache_path) / archiver / "index.json" return root.exists() def get_index(config, archiver): """ Get the contents of the archiver index file :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :return: The index data :rtype: ``dict`` """ root = pathlib.Path(config.cache_path) / archiver with (root / "index.json").open("r") as index_f: index = json.load(index_f) return index def get(config, archiver, revision): """ Get the data for a given revision :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :param revision: The revision ID :type revision: ``str`` :return: The data record for that revision :rtype: ``dict`` """ root = pathlib.Path(config.cache_path) / archiver # TODO : string escaping!!! with (root / f"{revision}.json").open("r") as rev_f: index = json.load(rev_f) return index PKAiiMz#n wily/config.py""" Configuration of wily TODO : Handle operator settings. Maybe a section for each operator and then pass kwargs to operators? TODO : Better utilise default values and factory in @dataclass to replace DEFAULT_CONFIG and replace the logic in load() to set default values. """ import configparser import pathlib import logging from dataclasses import dataclass, field from typing import Any, List import wily.operators as operators from wily.archivers import ARCHIVER_GIT logger = logging.getLogger(__name__) """ The default path name to the cache """ DEFAULT_CACHE_PATH = ".wily" @dataclass class WilyConfig(object): """ A data class to reflect the configurable options within Wily. """ operators: List archiver: Any path: str max_revisions: int cache_path: str = DEFAULT_CACHE_PATH targets: List[str] = None checkout_options: dict = field(default_factory=dict) def __post_init__(self): # Clone targets as a list of path if self.targets is None or "": self.targets = [self.path] # Default values for Wily """ The default operators """ DEFAULT_OPERATORS = { operators.OPERATOR_RAW.name, operators.OPERATOR_MAINTAINABILITY.name, operators.OPERATOR_CYCLOMATIC.name, } """ The name of the default archiver """ DEFAULT_ARCHIVER = ARCHIVER_GIT.name """ The default configuration file name """ DEFAULT_CONFIG_PATH = "wily.cfg" """ The default section name in the config """ DEFAULT_CONFIG_SECTION = "wily" """ The default maximum number of revisions to archiver """ DEFAULT_MAX_REVISIONS = 50 DEFAULT_PATH = "." """ The default configuration for Wily (if no config file exists) """ DEFAULT_CONFIG = WilyConfig( operators=DEFAULT_OPERATORS, archiver=DEFAULT_ARCHIVER, path=DEFAULT_PATH, max_revisions=DEFAULT_MAX_REVISIONS, ) """ Default table style in console. See tabulate docs for more. """ DEFAULT_GRID_STYLE = "fancy_grid" def load(config_path=DEFAULT_CONFIG_PATH): """ Load config file and set values to defaults where no present. :return: The configuration ``WilyConfig`` :rtype: :class:`wily.config.WilyConfig` """ if not pathlib.Path(config_path).exists(): logger.debug(f"Could not locate {config_path}, using default config.") return DEFAULT_CONFIG config = configparser.ConfigParser(default_section=DEFAULT_CONFIG_SECTION) config.read(config_path) operators = config.get( section=DEFAULT_CONFIG_SECTION, option="operators", fallback=DEFAULT_OPERATORS ) archiver = config.get( section=DEFAULT_CONFIG_SECTION, option="archiver", fallback=DEFAULT_ARCHIVER ) path = config.get(section=DEFAULT_CONFIG_SECTION, option="path", fallback=".") max_revisions = int( config.get( section=DEFAULT_CONFIG_SECTION, option="max_revisions", fallback=DEFAULT_MAX_REVISIONS, ) ) return WilyConfig( operators=operators, archiver=archiver, path=path, max_revisions=max_revisions ) PK\\MZσwily/archivers/__init__.pyfrom collections import namedtuple from dataclasses import dataclass class BaseArchiver(object): """Abstract Archiver Class""" def revisions(self, path, max_revisions): """ Get the list of revision :param path: the path :type path: ``str`` :param max_revisions: the maximum number of revisions :type max_revisions: ``int`` :return: A list of revisions :rtype: ``list`` of :class:`Revision` """ raise NotImplementedError() def checkout(self, revision, **options): """ Checkout a specific revision :param revision: The revision identifier :type revision: :class:`Revision` :param options: Any additional options :type options: ``dict`` """ raise NotImplementedError() @dataclass class Revision: key: str author_name: str author_email: str revision_date: str message: str from wily.archivers.git import GitArchiver """Type for an operator""" Archiver = namedtuple("Archiver", "name cls description") """Git Operator defined in `wily.archivers.git`""" ARCHIVER_GIT = Archiver(name="git", cls=GitArchiver, description="Git archiver") """Set of all available archivers""" ALL_ARCHIVERS = {ARCHIVER_GIT} def resolve_archiver(name): """ Get the :namedtuple:`wily.archivers.Archiver` for a given name :param name: The name of the archiver :return: The archiver type """ r = [archiver for archiver in ALL_ARCHIVERS if archiver.name == name.lower()] if not r: raise ValueError(f"Resolver {name} not recognised.") else: return r[0] PKmiM*3wily/archivers/git.pyfrom git import Repo import logging import pathlib from wily.archivers import BaseArchiver, Revision logger = logging.getLogger(__name__) class DirtyGitRepositoryError(Exception): def __init__(self, untracked_files): self.untracked_files = untracked_files self.message = "Dirty repository, make sure you commit/stash files first" class WilyIgnoreGitRepositoryError(Exception): def __init__(self): self.message = "Please add '.wily/' to .gitignore before running wily" class GitArchiver(BaseArchiver): name = "git" def __init__(self, config): self.repo = Repo(config.path) gitignore = pathlib.Path(config.path) / ".gitignore" if not gitignore.exists(): raise WilyIgnoreGitRepositoryError() with open(gitignore, "r") as gitignore_f: if ".wily/" not in gitignore_f.readlines(): raise WilyIgnoreGitRepositoryError() self.config = config self.current_branch = self.repo.active_branch assert not self.repo.bare, "Not a Git repository" def revisions(self, path, max_revisions): if self.repo.is_dirty(): raise DirtyGitRepositoryError(self.repo.untracked_files) revisions = [] for commit in self.repo.iter_commits( self.current_branch, max_count=self.config.max_revisions ): rev = Revision( key=commit.name_rev.split(" ")[0], author_name=commit.author.name, author_email=commit.author.email, revision_date=commit.committed_date, message=commit.message, ) revisions.append(rev) return revisions def checkout(self, revision, options): rev = revision.key self.repo.git.checkout(rev) def finish(self): # Make sure you checkout HEAD on the original branch when finishing self.repo.git.checkout(self.current_branch) PKbcLMwily/commands/__init__.pyPKAiiM1cU U wily/commands/build.py""" Builds a cache based on a source-control history """ from progress.bar import Bar from wily import logger import wily.cache as cache def build(config, archiver, operators): """ Build the history given a archiver and collection of operators. :param config: The wily configuration :type config: :namedtuple:`wily.config.WilyConfig` :param archiver: The archiver to use :type archiver: :namedtuple:`wily.archivers.Archiver` :param operators: The list of operators to execute :type operators: `list` of :namedtuple:`wily.operators.Operator` """ # Check for existence of cache, else provision if not cache.exists(config): logger.debug("Wily cache not found, creating.") cache.create(config) logger.debug("Created wily cache") logger.debug(f"Using {archiver.name} archiver module") archiver = archiver.cls(config) try: revisions = archiver.revisions(config.path, config.max_revisions) except Exception as e: logger.error(f"Failed to setup archiver: '{e.message}'") return if revisions is None or len(revisions) == 0: logger.warning("Could not find any revisions, using HEAD") revisions = [] # TODO: Create a special HEAD revision to use current state if cache.has_index(config, archiver.name): logger.debug("Found existing index, doing a revision diff") index = cache.get_index(config, archiver.name) # remove existing revisions from the list existing_revisions = [r["revision"] for r in index] revisions = [ revision for revision in revisions if revision.key not in existing_revisions ] else: index = [] logger.info( f"Found {len(revisions)} revisions from '{archiver.name}' archiver in '{config.path}'." ) _op_desc = ",".join([operator.name for operator in operators]) logger.info(f"Running operators - {_op_desc}") bar = Bar("Processing", max=len(revisions) * len(operators)) try: for revision in revisions: # Checkout target revision archiver.checkout(revision, config.checkout_options) # Build a set of operators _operators = [operator.cls(config) for operator in operators] stats_header = { "revision": revision.key, "author_name": revision.author_name, "author_email": revision.author_email, "date": revision.revision_date, "message": revision.message, "operators": _op_desc, } stats = stats_header.copy() stats["operator_data"] = {} for operator in _operators: logger.debug(f"Running {operator.name} operator on {revision.key}") stats["operator_data"][operator.name] = operator.run(revision, config) bar.next() index.append(stats_header) cache.store(config, archiver, revision, stats) cache.store_index(config, archiver, index) bar.finish() except Exception as e: if hasattr(e, "message"): logger.error(f"Failed to build cache: '{e.message}'") else: logger.error(f"Failed to build cache: '{e}'") finally: # Reset the archive after every run back to the head of the branch archiver.finish() PKygMwily/commands/graph.py""" Draw graph in HTML for a specific metric TODO: Somehow link to the rev-hash? TODO: Add multiple lines for multiple files TODO: Add multiple lines for multiple metrics(?) """ from wily import logger, format_datetime, format_revision import tabulate import pathlib from wily.config import DEFAULT_CACHE_PATH, DEFAULT_GRID_STYLE import wily.cache as cache from wily.operators import resolve_metric, MetricType import plotly.offline import plotly.plotly as py import plotly.graph_objs as go def graph(config, paths, metric): """ Graph information about the cache and runtime :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param paths: The path(s) to the files :type paths: ``list`` :param metric: The metric to report on :type metric: The metric :return: """ logger.debug("Running report command") data = [] operator, key = metric.split(".") metric = resolve_metric(metric) archivers = cache.list_archivers(config) for path in paths: x = [] y = [] for archiver in archivers: # We have to do it backwards to get the deltas between releases history = cache.get_index(config, archiver) ids = [rev["revision"] for rev in history[::-1]] labels = [ f"{rev['author_name']}
{rev['message']}" for rev in history[::-1] ] for rev in history[::-1]: revision_entry = cache.get(config, archiver, rev["revision"]) try: val = revision_entry["operator_data"][operator][path][key] y.append(val) except KeyError: y.append(0) finally: x.append(format_datetime(rev["date"])) # Create traces trace = go.Scatter( x=x, y=y, mode="lines+markers", name=f"{metric.description} for {path}", ids=ids, text=labels, xcalendar="gregorian", ) data.append(trace) plotly.offline.plot( {"data": data, "layout": go.Layout(title=f"History of {metric.description}")}, auto_open=True, ) PKygMh wily/commands/index.py""" Print information about the wily cache and what is in the index """ from wily import logger, format_date, format_revision, MAX_MESSAGE_WIDTH import tabulate import wily.cache as cache from wily.config import DEFAULT_GRID_STYLE def index(config, include_message=False): """ Show information about the cache and runtime :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: """ logger.debug("Running show command") logger.info("--------Configuration---------") logger.info(f"Path: {config.path}") logger.info(f"Archiver: {config.archiver}") logger.info(f"Operators: {config.operators}") logger.info("") logger.info("-----------History------------") data = [] archivers = cache.list_archivers(config) for archiver in archivers: history = cache.get_index(config, archiver) for rev in history: if include_message: data.append( ( format_revision(rev["revision"]), rev["author_name"], rev["message"][:MAX_MESSAGE_WIDTH], format_date(rev["date"]), ) ) else: data.append( ( format_revision(rev["revision"]), rev["author_name"], format_date(rev["date"]), ) ) if include_message: headers = ("Revision", "Author", "Message", "Date") else: headers = ("Revision", "Author", "Date") print( tabulate.tabulate( headers=headers, tabular_data=data, tablefmt=DEFAULT_GRID_STYLE ) ) PK\\Mݰrwily/commands/list_metrics.py""" List available metrics across all providers TODO : Only show metrics for the operators that the cache has? """ from wily import logger from wily.operators import ALL_OPERATORS from wily.config import DEFAULT_GRID_STYLE import tabulate def list_metrics(): for operator in ALL_OPERATORS: print(f"{operator.name} operator:") if len(operator.cls.metrics) > 0: print( tabulate.tabulate( headers=("Name", "Description", "Type"), tabular_data=operator.cls.metrics, tablefmt=DEFAULT_GRID_STYLE, ) ) else: logger.warning("No metrics available") PKAiiMmwily/commands/report.py""" TODO : Better error handling of wonky builds """ from wily import logger, format_date, format_revision, MAX_MESSAGE_WIDTH import tabulate import pathlib from wily.config import DEFAULT_CACHE_PATH, DEFAULT_GRID_STYLE import wily.cache as cache from wily.operators import resolve_metric, MetricType def report(config, path, metrics, n, include_message=False): """ Show information about the cache and runtime :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param path: The path to the file :type path: ``str`` :param metrics: Name of the metric to report on :type metrics: ``str`` :param n: Number of items to list :type n: ``int`` """ logger.debug("Running report command") logger.info(f"-----------History for {metrics}------------") data = [] last = None archivers = cache.list_archivers(config) metric_metas = [] for metric in metrics: operator, key = metric.split(".") metric = resolve_metric(metric) # Set the delta colors depending on the metric type if metric.measure == MetricType.AimHigh: good_color = 32 bad_color = 31 elif metric.measure == MetricType.AimLow: good_color = 31 bad_color = 32 elif metric.measure == MetricType.Informational: good_color = 33 bad_color = 33 metric_meta = { "key": key, "operator": operator, "good_color": good_color, "bad_color": bad_color, "title": metric.description, "type": metric.type, } metric_metas.append(metric_meta) for archiver in archivers: history = cache.get_index(config, archiver)[:n] # We have to do it backwards to get the deltas between releases history = history[::-1] last = {} for rev in history: revision_entry = cache.get(config, archiver, rev["revision"]) vals = [] for meta in metric_metas: try: logger.debug( f"Fetching metric {meta['key']} for {meta['operator']} in {path}" ) val = revision_entry["operator_data"][meta["operator"]][path][ meta["key"] ] last_val = last.get(meta["key"], None) # Measure the difference between this value and the last if meta["type"] in (int, float): if last_val: delta = val - last_val else: delta = 0 last[meta["key"]] = val else: # TODO : Measure ranking increases/decreases for str types? delta = 0 if delta == 0: delta_col = delta elif delta < 0: delta_col = f"\u001b[{meta['good_color']}m{delta:n}\u001b[0m" else: delta_col = f"\u001b[{meta['bad_color']}m+{delta:n}\u001b[0m" if meta["type"] in (int, float): k = f"{val:n} ({delta_col})" else: k = f"{val}" except KeyError: k = "Not found" vals.append(k) if include_message: data.append( ( format_revision(rev["revision"]), rev["message"][:MAX_MESSAGE_WIDTH], rev["author_name"], format_date(rev["date"]), *vals, ) ) else: data.append( ( format_revision(rev["revision"]), rev["author_name"], format_date(rev["date"]), *vals, ) ) descriptions = [meta["title"] for meta in metric_metas] if include_message: headers = ("Revision", "Message", "Author", "Date", *descriptions) else: headers = ("Revision", "Author", "Date", *descriptions) print( # But it still makes more sense to show the newest at the top, so reverse again tabulate.tabulate( headers=headers, tabular_data=data[::-1], tablefmt=DEFAULT_GRID_STYLE ) ) PKAiiM  wily/operators/__init__.pyfrom collections import namedtuple from enum import Enum class MetricType(Enum): """Type of metric, used in trends""" AimLow = 1 # Low is good, high is bad AimHigh = 2 # High is good, low is bad Informational = 3 # Doesn't matter Metric = namedtuple("Metric", "name description type measure") class BaseOperator(object): """Abstract Operator Class""" """Name of the operator""" name = "abstract" """Default settings""" defaults = {} """Available metrics as a list of tuple ("name", "description", "type", "metric_type")""" metrics = () """Which metric is the default to display in the report command""" default_metric_index = None def run(self, module, options): raise NotImplementedError() from wily.operators.mccabe import MccabeOperator from wily.operators.cyclomatic import CyclomaticComplexityOperator from wily.operators.maintainability import MaintainabilityIndexOperator from wily.operators.raw import RawMetricsOperator """Type for an operator""" Operator = namedtuple("Operator", "name cls description") OPERATOR_MCCABE = Operator( name="mccabe", cls=MccabeOperator, description="Number of branches via the Mccabe algorithm", ) OPERATOR_CYCLOMATIC = Operator( name="cyclomatic", cls=CyclomaticComplexityOperator, description="Cyclomatic Complexity of modules", ) OPERATOR_RAW = Operator( name="raw", cls=RawMetricsOperator, description="Raw Python statistics" ) OPERATOR_MAINTAINABILITY = Operator( name="maintainability", cls=MaintainabilityIndexOperator, description="Maintainability index (lines of code and branching)", ) """Set of all available operators""" ALL_OPERATORS = { OPERATOR_MCCABE, OPERATOR_CYCLOMATIC, OPERATOR_MAINTAINABILITY, OPERATOR_RAW, } def resolve_operator(name): """ Get the :namedtuple:`wily.operators.Operator` for a given name :param name: The name of the operator :return: The operator type """ r = [operator for operator in ALL_OPERATORS if operator.name == name.lower()] if not r: raise ValueError(f"Operator {name} not recognised.") else: return r[0] def resolve_operators(operators): return [resolve_operator(operator) for operator in operators] def resolve_metric(metric): """ Resolve metric key to a given target """ operator, key = metric.split(".") # TODO: Handle this better! return [ metric for metric in resolve_operator(operator).cls.metrics if metric[0] == key ][0] PK\\M^  wily/operators/cyclomatic.py""" Cyclomatic complexity metric for each function/method Provided by the radon library TODO : Figure out how to deal with the list metrics for functions? """ import radon.cli.harvest as harvesters from radon.cli import Config import radon from wily import logger from wily.operators import BaseOperator class CyclomaticComplexityOperator(BaseOperator): name = "cyclomatic" defaults = { "exclude": None, "ignore": None, "min": "A", "max": "F", "no_assert": True, "show_closures": False, "order": radon.complexity.SCORE, } metrics = () def __init__(self, config): # TODO: Import config for harvester from .wily.cfg logger.debug(f"Using {config.targets} with {self.defaults} for CC metrics") self.harvester = harvesters.CCHarvester( config.targets, config=Config(**self.defaults) ) def run(self, module, options): logger.debug("Running CC harvester") return dict(self.harvester.results) PKAiiM3=  !wily/operators/maintainability.pyimport radon.cli.harvest as harvesters from radon.cli import Config from wily import logger from wily.operators import BaseOperator, MetricType, Metric class MaintainabilityIndexOperator(BaseOperator): name = "maintainability" defaults = { "exclude": None, "ignore": None, "min": "A", "max": "C", "multi": True, "show": False, "sort": False, } metrics = ( Metric("rank", "Maintainability Ranking", str, MetricType.Informational), Metric("mi", "Maintainability Index", float, MetricType.AimLow), ) default_metric_index = 1 # MI def __init__(self, config): # TODO : Import config from wily.cfg logger.debug(f"Using {config.targets} with {self.defaults} for MI metrics") self.harvester = harvesters.MIHarvester( config.targets, config=Config(**self.defaults) ) def run(self, module, options): logger.debug("Running raw harvester") return dict(self.harvester.results) PKVNM:I5awily/operators/mccabe.pyfrom wily.operators import BaseOperator class MccabeOperator(BaseOperator): name = "mccabe" def __init__(self, config): pass PKAiiM]wily/operators/raw.pyimport radon.cli.harvest as harvesters from radon.cli import Config from wily import logger from wily.operators import BaseOperator, MetricType, Metric class RawMetricsOperator(BaseOperator): name = "raw" defaults = {"exclude": None, "ignore": None, "summary": False} metrics = ( Metric("loc", "Lines of Code", int, MetricType.AimLow), Metric("lloc", "L Lines of Code", int, MetricType.AimLow), Metric("sloc", "S Lines of Code", int, MetricType.AimLow), Metric("comments", "Multi-line comments", int, MetricType.AimHigh), Metric("multi", "Multi lines", int, MetricType.Informational), Metric("blank", "blank lines", int, MetricType.Informational), Metric( "single_comments", "Single comment lines", int, MetricType.Informational ), ) default_metric_index = 0 # LOC def __init__(self, config): # TODO: Use config from wily.cfg for harvester logger.debug(f"Using {config.targets} with {self.defaults} for Raw metrics") self.harvester = harvesters.RawHarvester( config.targets, config=Config(**self.defaults) ) def run(self, module, options): logger.debug("Running raw harvester") return dict(self.harvester.results) PK!H=d)*%wily-1.0.0.dist-info/entry_points.txtN+I/N.,()*̩z񹉙yV9\\PKILM]{],],wily-1.0.0.dist-info/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK!H>*RQwily-1.0.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&UrPK!HLO 2wily-1.0.0.dist-info/METADATA[nϧlZ8LuԺ[o5umap8!9,ghY( }(P`}>M̐%;7WF~Ԃ6rΙos³pMck^*! y]f|B"]8{sRe-r@/LE*Ј$$ȧ{,5$PEh&"WB/ 2-Isw :CfZjLU;Z拈2狎`3j3PeH:[ 4m`;]sӽ酶<_F8 $g7aDD Y?j`1d*eLpo%asZA!y60= c)0'ND/,Qv<Δi [Lp횃lڜS6SIGssXs gϞ=;>yIN^|uxzIBlF]quXM;t3z6UРJdUF*`OK(M%9DCKK%j/)Q7fOA6XV ?’GÈ(;ɹu \$%#:@_,HZza2 _ȝBhYvAbXwˮ9+e%R7xUh>a%",<޽ Uض쬦Q=DCB58F\s4A*8C "%avwc\xƄ 9I9AKA_==DM T;۴[#"| \Kkn푙6&$S }stz֖L23w FS[jrHrVO]N?yMyQB6cS sKvVxgkԐv)-DSQ,%=tj7+^h2>#s9p*4de'Vz.;ѱ;pM4o2X^6;M$bZvfOY]3q)]?3X) ®ܚo1[h ]9389:Za-X*qف?kmbR|@J\뿾yOv|g`i"UǧFw)v> |p|Ž(fߣojߘqXI?a0NqogIw{ „ YQa~8E=Ri2p?8w$ ^cG*> Hx?Qo4OпG*` pĢ^Q8f$'Y݀yeF.Z~HA? =R(wiē(#:"b? g<ѽqH y4h` q? 0xĉ?Ѯߏ_$pRGjD`<܇ X8$ A3| ^SuWsYWDNPT4Jis~s[BTk0>97I{Vt#r S0nh? z&|OZJ,{|ooXnkތ{|?( |m=1R~&&6@[b>-![Q^mܰgo'.O o=&xRYaIAA^@o{%x4untZEG&`}IRIo"{*|16n7 NDB`[iӤm&% 6kf˴M ٠mfYZ@P\cފ׼zu$D 4OybjeرY=4V:wV9~XI)=Fe}TLX9ztoGˎc^?dz]%|p|;kTu'M,p][SRkZiqqcYlJ#"KS1"9/Mv|%do0B]+5BZy? Лl/PK!H wily-1.0.0.dist-info/RECORDm˒:~؛;28$rG@ MB@. >qWw]LZr'!clR]}7fn e8]vo !0~8Mt1R54Xz^$ ?,/|@YUŋ2{oXK$E~WXց+VNe'SҢ,_Xo3]&N K-F,$}V[?0;%aG?CU 8vDOO5Zǿ%_΀ ^ѠPbHCt򞷛㗈_a_l?ΫK6դbrݥa-JWޤƥk l8jPQ9]U $g͐WIWpΫl-p[bǫ퀢G%(m}:R t>FK5!$Sp1_WWaba66'VW (cTF?9}*e7/`9%tta\ XxRd n]HkOL9)0 ahT:``}43E̖nd 5:ަj[*Lx`zOHfѿs`|$51-S"[ .1i{%q$h,I_g7 ɿ*iKQR]d66~JdU'lL1 *ŒO+UlT+%7hnDgog?%gq{$4&uݦi'{}TM 016l=S3qFKR9U{p+ۈЎK`|EF/ti7iZ6O@cuu`f;"M_97I/$eTbVfr}*ky2?>?oN_PKniM&wily/__init__.pyPKAiiM^>wily/__main__.pyPKAiiMEE 7wily/cache.pyPKAiiMz#n 3wily/config.pyPK\\MZσ?wily/archivers/__init__.pyPKmiM*3{Fwily/archivers/git.pyPKbcLMgNwily/commands/__init__.pyPKAiiM1cU U Nwily/commands/build.pyPKygM'\wily/commands/graph.pyPKygMh ,ewily/commands/index.pyPK\\MݰrWlwily/commands/list_metrics.pyPKAiiMmMowily/commands/report.pyPKAiiM  wily/operators/__init__.pyPK\\M^  Ӌwily/operators/cyclomatic.pyPKAiiM3=  !wily/operators/maintainability.pyPKVNM:I5abwily/operators/mccabe.pyPKAiiM](wily/operators/raw.pyPK!H=d)*%^wily-1.0.0.dist-info/entry_points.txtPKILM]{],],ʚwily-1.0.0.dist-info/LICENSEPK!H>*RQawily-1.0.0.dist-info/WHEELPK!HLO 2wily-1.0.0.dist-info/METADATAPK!H uwily-1.0.0.dist-info/RECORDPK