Skip to content

Commit

Permalink
Use black to format code.
Browse files Browse the repository at this point in the history
Closes #114
  • Loading branch information
theacodes committed Aug 24, 2018
1 parent 76dfb55 commit 88c0c21
Show file tree
Hide file tree
Showing 28 changed files with 823 additions and 810 deletions.
6 changes: 6 additions & 0 deletions .flake8
@@ -0,0 +1,6 @@
[flake8]
# Ignore black styles.
ignore = E501, W503
# Imports
import-order-style = google
application-import-names = nox,tests
65 changes: 30 additions & 35 deletions nox.py
Expand Up @@ -17,55 +17,50 @@
import nox


ON_APPVEYOR = os.environ.get('APPVEYOR') == 'True'
ON_APPVEYOR = os.environ.get("APPVEYOR") == "True"


@nox.session(python=['3.5', '3.6', '3.7'])
@nox.session(python=["3.5", "3.6", "3.7"])
def tests(session):
session.install('-r', 'requirements-test.txt')
session.install('-e', '.[tox_to_nox]')
tests = session.posargs or ['tests/']
session.install("-r", "requirements-test.txt")
session.install("-e", ".[tox_to_nox]")
tests = session.posargs or ["tests/"]
session.run(
'py.test', '--cov=nox', '--cov-config', '.coveragerc',
'--cov-report=', *tests)
session.notify('cover')
"py.test", "--cov=nox", "--cov-config", ".coveragerc", "--cov-report=", *tests
)
session.notify("cover")


@nox.session
def cover(session):
session.install('coverage')
session.install("coverage")
if ON_APPVEYOR:
fail_under = '--fail-under=99'
fail_under = "--fail-under=99"
else:
fail_under = '--fail-under=100'
session.run(
'coverage',
'report',
fail_under,
'--show-missing',
)
session.run('coverage', 'erase')
fail_under = "--fail-under=100"
session.run("coverage", "report", fail_under, "--show-missing")
session.run("coverage", "erase")


@nox.session
@nox.session(python="3.6")
def blacken(session):
session.install("black")
session.run("black", "nox", "tests", "nox.py", "setup.py")


@nox.session(python="3.6")
def lint(session):
session.install('flake8', 'flake8-import-order')
session.run(
'flake8',
'--import-order-style=google',
'--application-import-names=nox,tests',
'nox', 'tests')
session.install("flake8", "flake8-import-order", "black")
session.run("black", "--check", "nox", "tests", "nox.py", "setup.py")
session.run("flake8", "nox", "tests")


@nox.session(python='3.6')
@nox.session(python="3.6")
def docs(session):
session.run('rm', '-rf', 'docs/_build')
session.install('-r', 'requirements-test.txt')
session.install('.')
session.cd('docs')
session.run("rm", "-rf", "docs/_build")
session.install("-r", "requirements-test.txt")
session.install(".")
session.cd("docs")
session.run(
'sphinx-build',
'-b', 'html',
'-W',
'-d', '_build/doctrees',
'.', '_build/html')
"sphinx-build", "-b", "html", "-W", "-d", "_build/doctrees", ".", "_build/html"
)
2 changes: 1 addition & 1 deletion nox/__init__.py
Expand Up @@ -15,4 +15,4 @@
from nox._parametrize import parametrize_decorator as parametrize
from nox.registry import session_decorator as session

__all__ = ['parametrize', 'session']
__all__ = ["parametrize", "session"]
17 changes: 7 additions & 10 deletions nox/_parametrize.py
Expand Up @@ -36,8 +36,7 @@ def parametrize_decorator(arg_names, arg_values_list):

# Allow args to be specified as any of 'arg', 'arg,arg2' or ('arg', 'arg2')
if not isinstance(arg_names, (list, tuple)):
arg_names = list(
filter(None, [arg.strip() for arg in arg_names.split(',')]))
arg_names = list(filter(None, [arg.strip() for arg in arg_names.split(",")]))

# If there's only one arg_name, arg_values_list should be a single item
# or list. Transform it so it'll work with the combine step.
Expand All @@ -56,10 +55,9 @@ def parametrize_decorator(arg_names, arg_values_list):
call_specs.append(call_spec)

def inner(f):
previous_call_specs = getattr(f, 'parametrize', None)
new_call_specs = update_call_specs(
previous_call_specs, call_specs)
setattr(f, 'parametrize', new_call_specs)
previous_call_specs = getattr(f, "parametrize", None)
new_call_specs = update_call_specs(previous_call_specs, call_specs)
setattr(f, "parametrize", new_call_specs)
return f

return inner
Expand All @@ -79,10 +77,8 @@ def update_call_specs(call_specs, new_specs):


def generate_session_signature(func, call_spec):
args = [
'{}={}'.format(k, repr(call_spec[k]))
for k in sorted(call_spec.keys())]
return '({})'.format(', '.join(args))
args = ["{}={}".format(k, repr(call_spec[k])) for k in sorted(call_spec.keys())]
return "({})".format(", ".join(args))


def generate_calls(func, call_specs):
Expand All @@ -94,6 +90,7 @@ def make_call_wrapper(call_spec):
def call_wrapper(*args, **kwargs):
kwargs.update(call_spec)
return func(*args, **kwargs)

return call_wrapper

call = make_call_wrapper(call_spec)
Expand Down
34 changes: 16 additions & 18 deletions nox/command.py
Expand Up @@ -23,6 +23,7 @@

class CommandFailed(Exception):
"""Raised when an executed command returns a non-success status code."""

def __init__(self, reason=None):
super(CommandFailed, self).__init__(reason)
self.reason = reason
Expand All @@ -43,8 +44,8 @@ def which(program, path):
if full_path:
return full_path.strpath

logger.error('Program {} not found.'.format(program))
raise CommandFailed('Program {} not found'.format(program))
logger.error("Program {} not found.".format(program))
raise CommandFailed("Program {} not found".format(program))


def _clean_env(env):
Expand All @@ -55,27 +56,24 @@ def _clean_env(env):
clean_env = {}

# Ensure systemroot is passed down, otherwise Windows will explode.
clean_env['SYSTEMROOT'] = os.environ.get('SYSTEMROOT', '')
clean_env["SYSTEMROOT"] = os.environ.get("SYSTEMROOT", "")

for key, value in env.items():
key = key.decode('utf-8') if isinstance(key, bytes) else key
value = (
value.decode('utf-8') if isinstance(value, bytes) else value)
key = key.decode("utf-8") if isinstance(key, bytes) else key
value = value.decode("utf-8") if isinstance(value, bytes) else value
clean_env[key] = value

return clean_env


def run(args, *, env=None, silent=False, path=None,
success_codes=None, log=True):
def run(args, *, env=None, silent=False, path=None, success_codes=None, log=True):
"""Run a command-line program."""

if success_codes is None:
success_codes = [0]

cmd, args = args[0], args[1:]
full_cmd = '{} {}'.format(
cmd, ' '.join(args))
full_cmd = "{} {}".format(cmd, " ".join(args))

cmd_path = which(cmd, path)

Expand All @@ -85,22 +83,22 @@ def run(args, *, env=None, silent=False, path=None,
env = _clean_env(env)

try:
return_code, output = popen(
[cmd_path] + list(args),
silent=silent,
env=env)
return_code, output = popen([cmd_path] + list(args), silent=silent, env=env)

if return_code not in success_codes:
logger.error('Command {} failed with exit code {}{}'.format(
full_cmd, return_code, ':' if silent else ''))
logger.error(
"Command {} failed with exit code {}{}".format(
full_cmd, return_code, ":" if silent else ""
)
)

if silent:
sys.stderr.write(output)

raise CommandFailed('Returned code {}'.format(return_code))
raise CommandFailed("Returned code {}".format(return_code))

return output if silent else True

except KeyboardInterrupt:
logger.error('Interrupted...')
logger.error("Interrupted...")
raise
18 changes: 9 additions & 9 deletions nox/logger.py
Expand Up @@ -32,7 +32,7 @@ def success(self, msg, *args, **kwargs):


logging.setLoggerClass(LoggerWithSuccess)
logger = logging.getLogger('nox')
logger = logging.getLogger("nox")
logger.setLevel(logging.DEBUG)


Expand All @@ -52,18 +52,18 @@ def setup_logging(color): # pragma: no cover
"%(cyan)s%(name)s > %(log_color)s%(message)s",
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'blue',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
'SUCCESS': 'green'
}
"DEBUG": "cyan",
"INFO": "blue",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
"SUCCESS": "green",
},
)

handler.setFormatter(formatter)

root_logger.addHandler(handler)

# Silence noisy loggers
logging.getLogger('sh').setLevel(logging.WARNING)
logging.getLogger("sh").setLevel(logging.WARNING)
77 changes: 48 additions & 29 deletions nox/main.py
Expand Up @@ -42,55 +42,74 @@ def __init__(self, args):
self.posargs = args.posargs
self.report = args.report

if self.posargs and self.posargs[0] == '--':
if self.posargs and self.posargs[0] == "--":
self.posargs.pop(0)


def main():
parser = argparse.ArgumentParser(
description='nox is a Python automation toolkit.')
parser = argparse.ArgumentParser(description="nox is a Python automation toolkit.")
parser.add_argument(
'-f', '--noxfile', default='nox.py',
help='Location of the Python file containing nox sessions.')
"-f",
"--noxfile",
default="nox.py",
help="Location of the Python file containing nox sessions.",
)
parser.add_argument(
'-l', '--list-sessions', action='store_true',
help='List all available sessions and exit.')
"-l",
"--list-sessions",
action="store_true",
help="List all available sessions and exit.",
)
parser.add_argument(
'--envdir', default='.nox',
help='Directory where nox will store virtualenvs.')
"--envdir", default=".nox", help="Directory where nox will store virtualenvs."
)
parser.add_argument(
'-s', '-e', '--sessions', nargs='*',
help='Which sessions to run, by default, all sessions will run.')
"-s",
"-e",
"--sessions",
nargs="*",
help="Which sessions to run, by default, all sessions will run.",
)
parser.add_argument(
'-k', '--keywords',
help='Only run sessions that match the given expression.')
"-k", "--keywords", help="Only run sessions that match the given expression."
)
parser.add_argument(
'-r', '--reuse-existing-virtualenvs', action='store_true',
help='Re-use existing virtualenvs instead of recreating them.')
"-r",
"--reuse-existing-virtualenvs",
action="store_true",
help="Re-use existing virtualenvs instead of recreating them.",
)
parser.add_argument(
'--stop-on-first-error', action='store_true',
help='Stop after the first error.')
"--stop-on-first-error", action="store_true", help="Stop after the first error."
)
parser.add_argument(
'--report', default=None,
help='Output a report of all sessions.')
"--report", default=None, help="Output a report of all sessions."
)
parser.add_argument(
'--nocolor', default=not sys.stderr.isatty(), action='store_true',
help='Disable all color output.')
"--nocolor",
default=not sys.stderr.isatty(),
action="store_true",
help="Disable all color output.",
)
parser.add_argument(
'--forcecolor', default=False, action='store_true',
help=('Force color output, even if stdout is not an interactive '
'terminal.'))
"--forcecolor",
default=False,
action="store_true",
help=("Force color output, even if stdout is not an interactive " "terminal."),
)
parser.add_argument(
'posargs', nargs=argparse.REMAINDER,
help='Arguments that are passed through to the sessions.')
"posargs",
nargs=argparse.REMAINDER,
help="Arguments that are passed through to the sessions.",
)
parser.add_argument(
'--version', action='store_true',
help='Output the nox version and exit.')
"--version", action="store_true", help="Output the nox version and exit."
)

args = parser.parse_args()

if args.version:
dist = pkg_resources.get_distribution('nox')
dist = pkg_resources.get_distribution("nox")
print(dist.version, file=sys.stderr)
return

Expand Down

0 comments on commit 88c0c21

Please sign in to comment.