PK j?hMd\Ө wily/__init__.py"""
A Python application for tracking, reporting on timing and complexity in tests and applications.
"""
import colorlog
import datetime
__version__ = "0.8.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]
PK ~hM͡j. . wily/__main__.py"""
Main command line
TODO : Prompt the user for the specific metric in the graph and report commands?
"""
import os.path
import click
from wily import logger
from wily.cache import exists
from wily.config import load as load_config
from wily.config import DEFAULT_CONFIG_PATH, DEFAULT_CACHE_PATH, DEFAULT_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),
help="Root path to the project folder to scan",
)
@click.pass_context
def cli(ctx, debug, config, path):
"""Commands for creating and searching through history."""
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.option(
"-t",
"--target",
default=None,
type=click.Path(resolve_path=True),
multiple=True,
help="Subdirectories or files to scan",
)
@click.option(
"-o",
"--operators",
type=click.STRING,
help="List of operators, seperated by commas",
)
@click.pass_context
def build(ctx, max_revisions, target, 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 target:
logger.debug(f"Fixing targets to {target}")
config.targets = target
if operators:
logger.debug(f"Fixing operators to {operators}")
config.operators = operators.strip().split(",")
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.")
return -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.argument("metric")
@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, metric, number, message):
"""Show 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.")
return -1
from wily.commands.report import report
logger.debug(f"Running report on {file} for metric {metric}")
report(config=config, path=file, metric=metric, 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.")
return -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.")
return 0
if not yes:
p = input("Are you sure you want to delete wily cache? [y/N]")
if p.lower() != "y":
return 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.")
return -1
from wily.commands.list_metrics import list_metrics
list_metrics()
if __name__ == "__main__":
cli()
PK yhML,
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 import logger
def exists(config):
"""
Check whether the .wily/ directory exists
: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
: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
"""
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 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")
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 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
: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_index(config, archiver):
"""
Get the contents of the archiver index file
: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 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
PK 9~hMyA A wily/config.py"""
Configuration of wily
TODO : Handle operator settings. Maybe a section for each operator and then pass kwargs to operators?
TODO : Allow configuration of cache path (incase it needs to go in another folder)
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 = 100
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 PMZσ 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]
PK IRMpG wily/archivers/git.pyfrom git import Repo
import logging
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 GitArchiver(BaseArchiver):
name = "git"
def __init__(self, config):
self.repo = Repo(config.path)
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)
PK PM wily/commands/__init__.pyPK j?hM" wily/commands/build.py"""
Builds a cache based on a source-control history
TODO : Compare with existing files and cache results, currently just overwrites
"""
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
logger.info(
f"Found {len(revisions)} revisions from '{archiver.name}' archiver in '{config.path}'."
)
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
_op_desc = ",".join([operator.name for operator in operators])
logger.info(f"Running operators - {_op_desc}")
index = []
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()
PK aM wily/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,
)
PK (aMh 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 IRMݰr wily/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")
PK 7aMbس wily/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, metric, 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 metric: Name of the metric to report on
:type metric: ``str``
:param n: Number of items to list
:type n: ``int``
"""
logger.debug("Running report command")
logger.info(f"-----------History for {metric}------------")
data = []
last = None
operator, key = metric.split(".")
metric = resolve_metric(metric)
archivers = cache.list_archivers(config)
# 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
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]
for rev in history:
revision_entry = cache.get(config, archiver, rev["revision"])
try:
val = revision_entry["operator_data"][operator][path][key]
# Measure the difference between this value and the last
if metric.type in (int, float):
if last:
delta = val - last
else:
delta = 0
last = 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[{good_color}m{delta:n}\u001b[0m"
else:
delta_col = f"\u001b[{bad_color}m+{delta:n}\u001b[0m"
if metric.type in (int, float):
k = f"{val:n} ({delta_col})"
else:
k = f"{val}"
except KeyError:
k = "Not found"
finally:
if include_message:
data.append(
(
format_revision(rev["revision"]),
rev["message"][:MAX_MESSAGE_WIDTH],
rev["author_name"],
format_date(rev["date"]),
k,
)
)
else:
data.append(
(
format_revision(rev["revision"]),
rev["author_name"],
format_date(rev["date"]),
k,
)
)
if include_message:
headers = ("Revision", "Message", "Author", "Date", metric.description)
else:
headers = ("Revision", "Author", "Date", metric.description)
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
)
)
PK IRM z 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 = ()
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 h
PM^
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)
PK IRM
{ ! 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),
)
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)
PK PM:I5a wily/operators/mccabe.pyfrom wily.operators import BaseOperator
class MccabeOperator(BaseOperator):
name = "mccabe"
def __init__(self, config):
pass
PK j?hMx 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
),
)
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-0.8.0.dist-info/entry_points.txtN+I/N.,()*̩zyV9\\ PK tOM]{], ], wily-0.8.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>*R Q wily-0.8.0.dist-info/WHEELHM
K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&Ur PK !H
f 'B wily-0.8.0.dist-info/METADATA[nϧ]p5)$Qj7qn`a
CijrVnOP P E3i$=3CZĉVF] J,7£'TKl|dzфeS&u"ǵΫ>:FϦrs"cK(R^"Ybr!*iK dI6Vp EF_29E2Bϵ$SC0d$e!Q;P%y>qs:mi;3Bs>oά
+\9E#<m:,C:K@ίpɈ:Z+VRaїGӱPAJV(<4Ŵ.%})[ U'u?BQ輶
):._D}?s .iSt&dmrFD ^$.KW+]rjɇM,+5d*~׆4t36KKG99̜e}Bݷ>`[% BҲp"ZW%K!1N,ΩiWtWb6 cpqs2:2C9ЪOJN0V!3]5
K\Z1NTr `0g۷`˯O8D#hy<6H@QÝ"de%fBJҟLՁ*!YBB}aBuY(P.J
}%#D9૨p 3y#6yB$9Φ 4M*A"`rĴJ)TB@?C:Мw2%X+ plo}-@ꑩcH5`200zj4(ZgZ͑mhVXB=,eêSbYXJB-JY1C1%% DҀez!*5L ,8EJtA(H=Aqs-g9`xB* uZ1"SCK5 1!8fnAo@GTv*z6RM#u&KQcc#RZC2>h