Skip to content

Commit

Permalink
refactor: enforce Black lint style in CI and delint (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
crccheck authored Mar 28, 2023
1 parent 5e18211 commit d1e475f
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 99 deletions.
22 changes: 11 additions & 11 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ jobs:
- run: pip install -r requirements.txt
- run: make test

# lint:
# name: "Black"
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v3
# - name: Set up Python
# uses: actions/setup-python@v4
# with:
# python-version: "3.11"
# - run: pip install black
# - run: black --check .
lint:
name: "Black"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- run: pip install black
- run: black --check .
2 changes: 1 addition & 1 deletion project_runpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from .heidi import * # noqa: F401 F403
from .tim import * # noqa: F401 F403

__version__ = '1.0.1'
__version__ = "1.0.1"
58 changes: 30 additions & 28 deletions project_runpy/heidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,38 @@
"""
import logging

__all__ = ['ColorizingStreamHandler', 'ReadableSqlFilter']
__all__ = ["ColorizingStreamHandler", "ReadableSqlFilter"]


# Copyright (C) 2010-2012 Vinay Sajip. All rights reserved. Licensed under the new BSD license.
# https://gist.github.com/758430
class ColorizingStreamHandler(logging.StreamHandler):
# color names to indices
color_map = {
'black': 0,
'red': 1,
'green': 2,
'yellow': 3,
'blue': 4,
'magenta': 5,
'cyan': 6,
'white': 7,
"black": 0,
"red": 1,
"green": 2,
"yellow": 3,
"blue": 4,
"magenta": 5,
"cyan": 6,
"white": 7,
}

# levels to (background, foreground, bold/intense)
level_map = {
logging.DEBUG: (None, 'blue', False),
logging.INFO: (None, 'white', False),
logging.WARNING: (None, 'yellow', False),
logging.ERROR: (None, 'red', False),
logging.CRITICAL: ('red', 'white', True),
logging.DEBUG: (None, "blue", False),
logging.INFO: (None, "white", False),
logging.WARNING: (None, "yellow", False),
logging.ERROR: (None, "red", False),
logging.CRITICAL: ("red", "white", True),
}
csi = '\x1b['
reset = '\x1b[0m'
csi = "\x1b["
reset = "\x1b[0m"

@property
def is_tty(self):
isatty = getattr(self.stream, 'isatty', None)
isatty = getattr(self.stream, "isatty", None)
return isatty and isatty()

def emit(self, record):
Expand All @@ -45,7 +45,7 @@ def emit(self, record):
stream.write(message)
else:
self.output_colorized(message)
stream.write(getattr(self, 'terminator', '\n'))
stream.write(getattr(self, "terminator", "\n"))
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
Expand All @@ -64,25 +64,27 @@ def colorize(self, message, record):
if fg in self.color_map:
params.append(str(self.color_map[fg] + 30))
if bold:
params.append('1')
params.append("1")
if params:
message = ''.join((self.csi, ';'.join(params),
'm', message, self.reset))
message = "".join(
(self.csi, ";".join(params), "m", message, self.reset)
)
return message

def format(self, record):
message = logging.StreamHandler.format(self, record)
if self.is_tty:
# Don't colorize any traceback
parts = message.split('\n', 1)
parts = message.split("\n", 1)
parts[0] = self.colorize(parts[0], record)
message = '\n'.join(parts)
message = "\n".join(parts)
return message


# LOGGING FILTERS
#################


class ReadableSqlFilter(logging.Filter):
"""
A filter for more readable sql by stripping out the SELECT ... columns.
Expand Down Expand Up @@ -113,19 +115,19 @@ class ReadableSqlFilter(logging.Filter):
def filter(self, record):
# https://github.com/django/django/blob/febe136d4c3310ec8901abecca3ea5ba2be3952c/django/db/backends/utils.py#L106-L131
duration, sql, *__ = record.args
if not sql or 'SELECT' not in sql[:28]:
if not sql or "SELECT" not in sql[:28]:
# WISHLIST what's the most performant way to see if 'SELECT' was
# used?
return super().filter(record)

begin = sql.index('SELECT')
begin = sql.index("SELECT")
try:
end = sql.index('FROM', begin + 6)
end = sql.index("FROM", begin + 6)
except ValueError: # not all SELECT statements also have a FROM
return super().filter(record)

sql = '{0}...{1}'.format(sql[:begin + 6], sql[end:])
sql = "{0}...{1}".format(sql[: begin + 6], sql[end:])
# Drop "; args=%s" to shorten logging output
record.msg = '(%.3f) %s'
record.msg = "(%.3f) %s"
record.args = (duration, sql)
return super().filter(record)
18 changes: 12 additions & 6 deletions project_runpy/tim.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,26 @@
import os


__all__ = ['ImproperlyConfigured', 'env', ]
__all__ = [
"ImproperlyConfigured",
"env",
]


class ImproperlyConfigured(Exception):
"""ForgotPantsException"""

pass


class _Env(dict):
"""A wrapper around os.environ that supports environments and `Boolean`."""

def __init__(self):
self.update(os.environ.copy())

def parse_bool(self, value):
return str(value).lower() not in ('false', '0', 'f')
return str(value).lower() not in ("false", "0", "f")

def get(self, key, default=None, type_func=None, **defaults):
"""
Expand All @@ -38,12 +43,12 @@ def get(self, key, default=None, type_func=None, **defaults):
env.get('DEBUG', FALSE, type_func=bool, TEST=False) # combine it
"""
environment = os.environ.get('ENVIRONMENT')
environment = os.environ.get("ENVIRONMENT")
default = defaults.get(environment, default)
value = os.environ.get(key, default)
if value is None and type_func is None:
# return early to prevent returning 'None'
return ''
return ""
if type_func is None:
# guess the type_func
type_func = str if default is None else default.__class__
Expand All @@ -65,9 +70,10 @@ def require(self, key, default=None, *args, **kwargs):
"""
# yeah, I could check the inputs and do stuff, but I feel like wrapping.
result = self.get(key, default, *args, **kwargs)
if result == '':
if result == "":
raise ImproperlyConfigured(
'Environment variable not found: {0}'.format(key))
"Environment variable not found: {0}".format(key)
)
return result


Expand Down
Loading

0 comments on commit d1e475f

Please sign in to comment.