Skip to content

Capture warnings without suppressing them #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/pyproject_hooks/_in_process/_in_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,32 @@ def build_sdist(sdist_directory, config_settings):
}


class _capture_warnings:
"""Context manager to capture warnings while still showing them to the caller."""

def __init__(self):
self._captured_warnings = []
self._old_showwarning = None

def _showwarning(self, message, category, filename, lineno, file=None, line=None):
# Capture the warning
self._captured_warnings.append(
warnings.WarningMessage(message, category, filename, lineno, file, line)
)
# Call the original showwarning to display the warning
if self._old_showwarning is not None:
self._old_showwarning(message, category, filename, lineno, file, line)

def __enter__(self):
self._old_showwarning = warnings.showwarning
warnings.showwarning = self._showwarning
return self._captured_warnings

def __exit__(self, exc_type, exc_value, traceback):
warnings.showwarning = self._old_showwarning
self._old_showwarning = None


def main():
if len(sys.argv) < 3:
sys.exit("Needs args: hook_name, control_dir")
Expand All @@ -369,7 +395,7 @@ def main():

hook_input = read_json(pjoin(control_dir, "input.json"))

with warnings.catch_warnings(record=True) as captured_warnings:
with _capture_warnings() as captured_warnings:
json_out = {"unsupported": False, "return_val": None}
try:
json_out["return_val"] = hook(**hook_input["kwargs"])
Expand Down
Loading