Skip to content

Commit

Permalink
Update the warning format to be more readable
Browse files Browse the repository at this point in the history
  • Loading branch information
pvandyken committed Feb 23, 2024
1 parent d3f1d74 commit 96b13c0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions snakebids/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

__submodules__ = ["core", "paths"]

from snakebids import _warningformat # noqa: F401

# isort: split
# <AUTOGEN_INIT>
import lazy_loader
Expand Down
52 changes: 52 additions & 0 deletions snakebids/_warningformat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from __future__ import annotations

import textwrap
import warnings
from pathlib import Path

from colorama import Fore, Style

WARN_TEMPLATE = f"""\
{Fore.RED}{Style.BRIGHT}[{{category}}]{Style.NORMAL} {{filename}}:{{lineno}} \
{Fore.RESET}{{line}}
{{message}}
"""


def formatwarning(
message: Warning | str,
category: type[Warning],
filename: str,
lineno: int,
line: str | None,
):
"""Format warning messages."""
if line is None:
with Path(filename).open() as f:
for _ in range(lineno):
line = f.readline().strip()

return WARN_TEMPLATE.format(
message=textwrap.indent(
"\n".join(
"\n".join(
textwrap.wrap(
line,
width=80,
)
)
for line in (
message.args[0] if isinstance(message, Warning) else message
).splitlines()
),
prefix=" ",
),
category=category.__name__,
filename=filename,
lineno=lineno,
line=line,
)


warnings.formatwarning = formatwarning

0 comments on commit 96b13c0

Please sign in to comment.