Skip to content

Commit

Permalink
pyp: __pyp_before__
Browse files Browse the repository at this point in the history
  • Loading branch information
hauntsaninja committed Nov 3, 2024
1 parent 5af2a58 commit 3d382a3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pyp.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,17 @@ def parse_input(code: List[str]) -> ast.Module:
raise PypError("".join(message).strip()) from e

self.before_tree = parse_input(before)
if "__pyp_before__" in config.name_to_def:
config_before = config.parts[config.name_to_def["__pyp_before__"]]
if not isinstance(config_before, ast.FunctionDef):
raise PypError("Config __pyp_before__ must be a function")
self.before_tree.body = config_before.body + self.before_tree.body

self.tree = parse_input(code)

self.after_tree = parse_input(after)
if "__pyp_after__" in config.name_to_def:
raise PypError("Config __pyp_after__ not supported")

f = NameFinder(self.before_tree, self.tree, self.after_tree)
self.defined: Set[str] = f.top_level_defined
Expand Down
20 changes: 20 additions & 0 deletions tests/test_pyp.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,26 @@ def test_config_conditional_current_shortcoming(config_mock):
compare_scripts(run_pyp(["--explain", "unparse(ast.parse('x')); pass"]), script3)


@patch("pyp.get_config_contents")
def test_config_pyp_before(config_mock):
config_mock.return_value = """
import signal
import sys
def __pyp_before__():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
"""
script = r"""#!/usr/bin/env python3
import signal
import sys
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
for x in sys.stdin:
x = x.rstrip('\n')
if x is not None:
print(x)
"""
compare_scripts(run_pyp(["--explain", "x"]), script)


def test_config_end_to_end(monkeypatch, capsys):
with tempfile.NamedTemporaryFile("w") as f:
config = "def foo(): return 1"
Expand Down

0 comments on commit 3d382a3

Please sign in to comment.