Skip to content

Commit

Permalink
Add black as code formatting tool
Browse files Browse the repository at this point in the history
* Add black tooling
* Reformat project with black
  • Loading branch information
Nicoretti committed Jan 30, 2022
1 parent 4546976 commit 7b40916
Show file tree
Hide file tree
Showing 16 changed files with 432 additions and 329 deletions.
3 changes: 3 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ Prysk
.. image:: https://coveralls.io/repos/github/Nicoretti/prysk/badge.svg?branch=master
:target: https://coveralls.io/github/Nicoretti/prysk?branch=master

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black

.. image:: https://img.shields.io/badge/pypi%20package-available-blue.svg
:target: https://pypi.org/project/prysk/

Expand Down
40 changes: 19 additions & 21 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,60 +17,58 @@

# -- Project information -----------------------------------------------------

project = 'prysk'
author = 'Brodie Rao, Nicola Coretti & Contributors'
project = "prysk"
author = "Brodie Rao, Nicola Coretti & Contributors"
copyright = author
# The full version, including alpha/beta/rc tags
release = '0.9.0'
release = "0.9.0"

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx_rtd_theme'
]
extensions = ["sphinx_rtd_theme"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

html_context = {
"display_github": True,
"github_user": "Nicoretti",
"github_repo": project,
"github_version": "master",
"conf_py_path": "/docs/",
"source_suffix": 'rst',
"source_suffix": "rst",
}

html_theme_options = {
'logo_only': False,
'display_version': True,
'prev_next_buttons_location': 'bottom',
'style_external_links': False,
'vcs_pageview_mode': '',
"logo_only": False,
"display_version": True,
"prev_next_buttons_location": "bottom",
"style_external_links": False,
"vcs_pageview_mode": "",
# Toc options
'collapse_navigation': True,
'sticky_navigation': True,
'navigation_depth': 4,
'includehidden': True,
'titles_only': False,
"collapse_navigation": True,
"sticky_navigation": True,
"navigation_depth": 4,
"includehidden": True,
"titles_only": False,
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
2 changes: 1 addition & 1 deletion prysk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from prysk.application import main
from prysk._test import test, testfile

__all__ = ['main', 'test', 'testfile']
__all__ = ["main", "test", "testfile"]
79 changes: 43 additions & 36 deletions prysk/_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import difflib
import re

__all__ = ['esc', 'glob', 'regex', 'unified_diff']
__all__ = ["esc", "glob", "regex", "unified_diff"]


def _regex(pattern, s):
Expand All @@ -14,7 +14,7 @@ def _regex(pattern, s):
[True, False]
"""
try:
return re.match(pattern + br'\Z', s)
return re.match(pattern + rb"\Z", s)
except re.error:
return False

Expand All @@ -29,57 +29,57 @@ def _glob(el, l):
True
"""
i, n = 0, len(el)
res = b''
res = b""
while i < n:
c = el[i:i + 1]
c = el[i : i + 1]
i += 1
if c == b'\\' and el[i] in b'*?\\':
res += el[i - 1:i + 1]
if c == b"\\" and el[i] in b"*?\\":
res += el[i - 1 : i + 1]
i += 1
elif c == b'*':
res += b'.*'
elif c == b'?':
res += b'.'
elif c == b"*":
res += b".*"
elif c == b"?":
res += b"."
else:
res += re.escape(c)
return _regex(res, l)


def _matchannotation(keyword, matchfunc, el, l):
"""Apply match function based on annotation keyword"""
ann = b' (%s)\n' % keyword
return el.endswith(ann) and matchfunc(el[:-len(ann)], l[:-1])
ann = b" (%s)\n" % keyword
return el.endswith(ann) and matchfunc(el[: -len(ann)], l[:-1])


def regex(el, l):
"""Apply a regular expression match to a line annotated with '(re)'"""
return _matchannotation(b're', _regex, el, l)
return _matchannotation(b"re", _regex, el, l)


def glob(el, l):
"""Apply a glob match to a line annotated with '(glob)'"""
return _matchannotation(b'glob', _glob, el, l)
return _matchannotation(b"glob", _glob, el, l)


def esc(el, l):
"""Apply an escape match to a line annotated with '(esc)'"""
ann = b' (esc)\n'
ann = b" (esc)\n"

if el.endswith(ann):
el = codecs.escape_decode(el[:-len(ann)])[0] + b'\n'
el = codecs.escape_decode(el[: -len(ann)])[0] + b"\n"
if el == l:
return True

if l.endswith(ann):
l = codecs.escape_decode(l[:-len(ann)])[0] + b'\n'
l = codecs.escape_decode(l[: -len(ann)])[0] + b"\n"
return el == l


class _SequenceMatcher(difflib.SequenceMatcher, object):
"""Like difflib.SequenceMatcher, but supports custom match functions"""

def __init__(self, *args, **kwargs):
self._matchers = kwargs.pop('matchers', [])
self._matchers = kwargs.pop("matchers", [])
super(_SequenceMatcher, self).__init__(*args, **kwargs)

def _match(self, el, l):
Expand All @@ -102,17 +102,25 @@ def find_longest_match(self, alo, ahi, blo, bhi):
# expected output) with b's line (the actual output).
self.a[alo + n] = line
matches.append((n, el))
ret = super(_SequenceMatcher, self).find_longest_match(alo, ahi,
blo, bhi)
ret = super(_SequenceMatcher, self).find_longest_match(alo, ahi, blo, bhi)
# Restore the lines replaced above. Otherwise, the diff output
# would seem to imply that the tests never had any regexes/globs.
for n, el in matches:
self.a[alo + n] = el
return ret


def unified_diff(l1, l2, fromfile=b'', tofile=b'', fromfiledate=b'',
tofiledate=b'', n=3, lineterm=b'\n', matchers=None):
def unified_diff(
l1,
l2,
fromfile=b"",
tofile=b"",
fromfiledate=b"",
tofiledate=b"",
n=3,
lineterm=b"\n",
matchers=None,
):
r"""Compare two sequences of lines; generate the delta as a unified diff.
This is like difflib.unified_diff(), but allows custom matchers.
Expand All @@ -136,27 +144,26 @@ def unified_diff(l1, l2, fromfile=b'', tofile=b'', fromfiledate=b'',
for group in matcher.get_grouped_opcodes(n):
if not started:
if fromfiledate:
fromdate = b'\t' + fromfiledate
fromdate = b"\t" + fromfiledate
else:
fromdate = b''
fromdate = b""
if tofiledate:
todate = b'\t' + tofiledate
todate = b"\t" + tofiledate
else:
todate = b''
yield b'--- ' + fromfile + fromdate + lineterm
yield b'+++ ' + tofile + todate + lineterm
todate = b""
yield b"--- " + fromfile + fromdate + lineterm
yield b"+++ " + tofile + todate + lineterm
started = True
i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
yield (b'@@ -%d,%d +%d,%d @@' % (i1 + 1, i2 - i1, j1 + 1, j2 - j1) +
lineterm)
yield (b"@@ -%d,%d +%d,%d @@" % (i1 + 1, i2 - i1, j1 + 1, j2 - j1) + lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
if tag == "equal":
for line in l1[i1:i2]:
yield b' ' + line
yield b" " + line
continue
if tag == 'replace' or tag == 'delete':
if tag == "replace" or tag == "delete":
for line in l1[i1:i2]:
yield b'-' + line
if tag == 'replace' or tag == 'insert':
yield b"-" + line
if tag == "replace" or tag == "insert":
for line in l2[j1:j2]:
yield b'+' + line
yield b"+" + line
22 changes: 14 additions & 8 deletions prysk/_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import subprocess
import sys

__all__ = ['PIPE', 'STDOUT', 'execute']
__all__ = ["PIPE", "STDOUT", "execute"]

PIPE = subprocess.PIPE
STDOUT = subprocess.STDOUT
Expand All @@ -18,8 +18,7 @@ def _makeresetsigpipe():
Python's SIGPIPE handler (SIG_IGN) from being inherited by the
child process.
"""
if (sys.platform == 'win32' or
getattr(signal, 'SIGPIPE', None) is None):
if sys.platform == "win32" or getattr(signal, "SIGPIPE", None) is None:
return None
return lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)

Expand All @@ -43,12 +42,19 @@ def execute(args, stdin=None, stdout=None, stderr=None, cwd=None, env=None):
This function returns a 2-tuple of (output, returncode).
"""
if sys.platform == 'win32':
if sys.platform == "win32":
args = [os.fsdecode(arg) for arg in args]

p = subprocess.Popen(args, stdin=PIPE, stdout=stdout, stderr=stderr,
cwd=cwd, env=env, bufsize=-1,
preexec_fn=_makeresetsigpipe(),
close_fds=os.name == 'posix')
p = subprocess.Popen(
args,
stdin=PIPE,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=env,
bufsize=-1,
preexec_fn=_makeresetsigpipe(),
close_fds=os.name == "posix",
)
out, err = p.communicate(stdin)
return out, p.returncode
31 changes: 20 additions & 11 deletions prysk/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@

from prysk._test import testfile

__all__ = ['runtests']
__all__ = ["runtests"]

if sys.platform == "win32":

if sys.platform == 'win32':
def _walk(top):
top = os.fsdecode(top)
for root, dirs, files in os.walk(top):
yield (os.fsencode(root),
[os.fsencode(p) for p in dirs],
[os.fsencode(p) for p in files])
yield (
os.fsencode(root),
[os.fsencode(p) for p in dirs],
[os.fsencode(p) for p in files],
)

else:
_walk = os.walk

Expand All @@ -25,10 +29,10 @@ def _findtests(paths):
for p in paths:
if os.path.isdir(p):
for root, dirs, files in _walk(p):
if os.path.basename(root).startswith(b'.'):
if os.path.basename(root).startswith(b"."):
continue
for f in sorted(files):
if not f.startswith(b'.') and f.endswith(b'.t'):
if not f.startswith(b".") and f.endswith(b".t"):
yield os.path.normpath(os.path.join(root, f))
else:
yield os.path.normpath(p)
Expand Down Expand Up @@ -75,7 +79,7 @@ def runtests(paths, tmpdir, shell, indent=2, cleanenv=True, debug=False):

basename = os.path.basename(path)
if basename in basenames:
basename = basename + b'-%d' % i
basename = basename + b"-%d" % i
else:
basenames.add(basename)

Expand All @@ -84,8 +88,13 @@ def test():
testdir = os.path.join(tmpdir, basename)
os.mkdir(testdir)
with _cwd(testdir):
return testfile(abspath, shell, indent=indent,
cleanenv=cleanenv, debug=debug,
testname=path)
return testfile(
abspath,
shell,
indent=indent,
cleanenv=cleanenv,
debug=debug,
testname=path,
)

yield (path, test)

0 comments on commit 7b40916

Please sign in to comment.