Skip to content

Commit

Permalink
Fix: handle verbose include/exclude patterns in pyproject.toml
Browse files Browse the repository at this point in the history
If a verbose pattern was being used in pyproject.toml, the
patterns did not function correctly. For instance, the pattern

exclude = '''
(
/(
  folder1
| folder2
)/
)
'''

does not function properly. This pattern is inspired by the
pattern that black themselves use:
https://github.com/python/black/blob/master/pyproject.toml

Solve this issue by removing newlines, and formatting
the pattern before using it. This is done the same way
as black themselves are doing it.
  • Loading branch information
JKitok authored and paddycarey committed Sep 2, 2020
1 parent 70b8749 commit d79e688
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
12 changes: 11 additions & 1 deletion pytest_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ def __init__(self, fspath, parent):
self.add_marker("black")
try:
with open("pyproject.toml") as toml_file:
self.pyproject = toml.load(toml_file)["tool"]["black"]
settings = toml.load(toml_file)["tool"]["black"]
if "include" in settings.keys():
settings["include"] = self._re_fix_verbose(settings["include"])
if "exclude" in settings.keys():
settings["exclude"] = self._re_fix_verbose(settings["exclude"])
self.pyproject = settings
except Exception:
self.pyproject = {}

Expand Down Expand Up @@ -97,6 +102,11 @@ def _excluded(self):
return False
return re.search(self.pyproject["exclude"], str(self.fspath))

def _re_fix_verbose(self, regex):
if "\n" in regex:
regex = "(?x)" + regex
return re.compile(regex)


class BlackError(Exception):
pass
37 changes: 37 additions & 0 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,43 @@ def hello():
result.assert_outcomes(skipped=1, passed=0)


def test_exclude_folder(testdir):
"""Assert test is skipped for files in a folder
"""
testdir.makefile(
"pyproject.toml",
"""
[tool.black]
exclude = '''
(
/(
first_folder
| ignore_folder
)/
)
'''
""",
)
p = testdir.makepyfile(
"""
def hello():
print("Hello, world!")
"""
)
# replace trailing newline (stripped by testdir.makepyfile)
p = p.write(p.read() + "\n")

# Move file into folder that should be excluded
ignore_folder = testdir.mkdir("ignore_folder")
testdir.run("mv", "test_exclude_folder.py", ignore_folder)

# Rename pyproject.toml ¯\_(ツ)_/¯
testdir.run("mv", "test_exclude_folder.pyproject.toml", "pyproject.toml")

result = testdir.runpytest("--black")
result.assert_outcomes(skipped=1, passed=0)


def test_include(testdir):
"""Assert test is not skipped if path is included but not excluded
"""
Expand Down

0 comments on commit d79e688

Please sign in to comment.